首页 > 代码库 > [php学习]单例模式

[php学习]单例模式

/** 2.Singleton*/class Singleton{	private static $instance = null;	public static function getInstance(){		if (!isset(self::$instance)){              $c = __CLASS__;              self::$instance = new $c;           }  		return self::$instance;	}	public function eventResult($id){		return $id;	}	protected function __construct()    {    }    private function __clone()    {    }    private function __wakeup()    {    }}class SingletonChild extends Singleton{}$obj = Singleton::getInstance();var_dump($obj === Singleton::getInstance());           $anotherObj = SingletonChild::getInstance();var_dump($anotherObj === Singleton::getInstance());     var_dump($anotherObj === SingletonChild::getInstance()); $objSingle = Singleton::getInstance();$result = $objSingle->eventResult(100);print_r($result);

注意的是对于:__construct,__clone,__wakeup 的修饰符设定防止被实例破坏单例。

[php学习]单例模式