【发布时间】:2014-12-26 03:37:26
【问题描述】:
我是 PHP 新手。 这是根据phptherightway.com 的标准单例模式示例:
<?php
class Singleton
{
public static function getInstance()
{
static $instance = null;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
protected function __construct()
{
}
private function __clone()
{
}
private function __wakeup()
{
}
}
class SingletonChild extends Singleton
{
}
$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance()); // bool(true)
$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance()); // bool(false)
var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)
问题在这一行:
static $instance = null;
if (null === $instance) {
$instance = new static();
}
据我所知,if (null === $instance) 始终为 TRUE,因为每次我调用 getInstance() 方法时,变量 $instance 总是被设置为 null,并且总是会创建一个新实例。
所以这不是一个真正的单例。你能解释一下吗?
【问题讨论】:
-
静态 $instance = null;将仅在第一次函数调用时执行 - 在其他情况下将被忽略
标签: php oop design-patterns singleton