目的:
针对一个类,永远只创建一个对象,PHP实现:
//单例模式代码实现核心
class Singleton {
//私有静态成员变量,保存全局实例
private static $instance = null;
//私有构造方法,保证外界无法直接实例化
final private function __construct() { }
//静态方法,返回此类唯一实例
public static function getInstance() {
if(!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
//防止克隆
final public function __clone() {
throw new Exception("Error:禁止克隆.");
}
}
$s = Singleton::getInstance();