<?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
网友评论