那么单例模式呢?


What about singleton pattern

我正在寻找有关单例模式的信息,我发现:http://www.php.net/manual/en/language.oop5.patterns.php#95196

我不明白:

final static public function getInstance()
{
    static $instance = null;
    return $instance ?: $instance = new static;
}

如果它设置$instance为null,为什么这样返回?为什么不在类的全局"空间"中创建$instance而不在getInstance中将其设置为null ?

不能用非静态值初始化类变量,所以

class X {
    $instance = new SomeObj();
}

是不允许的

你发布的代码是一种方式去确保只有一个类的实例被定义。

static $instance = null;

将创建变量,并在第一次调用该方法时将其设置为null。之后,由于它被声明为static, PHP将忽略这一行。

则其他代码如下所示:

if (isnull($instance)) {
    ... first time through this method, so instantiate the object
    $instance = new someobj;
}
return $instance;

以下链接对理解单例模式很有帮助。

维基百科

PHP模式

在这个特定的示例中,在函数调用中,$instance前面加了static关键字。这意味着变量在调用函数之间保留它的状态(值)。无效化只会在函数的初始调用中发生一次。
顺便说一句,这是C实现单例的方式…