经典的单例模式代码如下
class Singleton
{
private static $instance;
// 防止外部实例化
private function __construct(){}
// 防止克隆
private function __clone(){}
// 防止 serialize
private function __sleep(){}
// 防止 unserialize
private function __wakeup(){}
public function getInstance()
{
if (self::$instance == null) {
self::$instance = new self;
}
return self::$instance;
}
}
如果希望能够序列化,需要如下改动
class Singleton
{
private static $instance;
// 防止外部实例化
private function __construct(){}
// 防止克隆
private function __clone(){}
// 反序列化后反馈该对象
private function __wakeup()
{
self::$instance = $this;
}
public function getInstance()
{
if (self::$instance == null) {
self::$instance = new self;
}
return self::$instance;
}
}