Dai*_*ail 2 php singleton design-patterns
我一直在寻找有关单身模式的信息,我发现:http://www.php.net/manual/en/language.oop5.patterns.php#95196
我不明白:
final static public function getInstance()
{
static $instance = null;
return $instance ?: $instance = new static;
}
Run Code Online (Sandbox Code Playgroud)
如果将$ instance设置为null,为什么会这样返回?为什么不在类的全局"空间"中创建$ instance而不在getInstance中将其设置为null?
您不能使用非静态值启动类变量,因此
class X {
$instance = new SomeObj();
}
Run Code Online (Sandbox Code Playgroud)
是不允许的.
您发布的代码是确保仅定义该类的一个实例的一种方法.
static $instance = null;
Run Code Online (Sandbox Code Playgroud)
将创建变量并将其设置为null第一次调用该方法.在那之后,sicne被宣布static,PHP将忽略该行.
然后其他代码可以看作如下:
if (isnull($instance)) {
... first time through this method, so instantiate the object
$instance = new someobj;
}
return $instance;
Run Code Online (Sandbox Code Playgroud)