我是 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
并且总是会创建一个新实例。
所以这不是真正的单例。你能解释一下吗?
最佳答案
在此处查看“示例 #5 静态变量的使用示例”: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static
“现在,$a 仅在第一次调用函数时初始化,每次调用 test() 函数时,它都会打印 $a 的值并递增它。”
关于php - PHP 中的单例模式示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647184/