单身模式怎么样?

时间:2011-10-31 15:59:57

标签: php design-patterns singleton

我一直在寻找有关单身人士模式的信息,我发现: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?

3 个答案:

答案 0 :(得分:6)

您无法使用非静态值启动类变量,因此

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

是不允许的。

您发布的代码是确保只定义该类的一个实例的一种方法。

static $instance = null;

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

然后其他代码可以看作如下:

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

答案 1 :(得分:0)

查找以下有助于理解单例模式的链接。

Wikipedia

PHP Patterns

答案 2 :(得分:0)

在此特定示例中,$instance在函数调用内部以static关键字开头。这意味着变量在函数调用之间保持它的状态(值)。在初始调用函数时,归零只会发生一次 b.t.w.这是做单身人士的C方式......

相关问题