<?php
/**
* 单例模式实现
*/
class Singleton
{
	//静态变量保存全局实例
	private static $instance = null;

	private function __clone()
	{
		//私有构造函数,防止外界实例化对象
	}

	private function __construct()
	{
		//私有克隆函数,防止外界克隆对象
	}

	//静态方法,单例统一访问入口
	public static function getInstance()
	{
		if (self::$instance instanceof Singleton) {
			echo "return exist instance\n";
			return self::$instance;
		}
		self::$instance = new Singleton();
		echo "return new instance\n";
		return self::$instance;
	}
}

$a = Singleton::getInstance();//output: return new instance
$a = Singleton::getInstance();//output: return exist instance

相关文章:

  • 2021-10-06
  • 2022-02-14
  • 2021-11-09
  • 2021-08-28
  • 2022-01-20
猜你喜欢
  • 2021-08-20
  • 2021-09-08
  • 2022-12-23
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案