The ceiling ε=ε=ε=(~ ̄▽ ̄)~

PHP实现单例模式

<?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
posted @ 2018-10-29 11:20  ImClive  阅读(182)  评论(0编辑  收藏  举报