Php 那么单例模式呢

Php 那么单例模式呢,php,design-patterns,singleton,Php,Design Patterns,Singleton,我在寻找关于单身模式的信息,我发现: 我不明白: final static public function getInstance() { static $instance = null; return $instance ?: $instance = new static; } 如果它将$instance设置为null,为什么会出现这种返回?为什么不在类的全局“空间”中创建$instance而不在getInstance中将其设置为null?找到以下链接,这些链接对于理解单例

我在寻找关于单身模式的信息,我发现:

我不明白:

final static public function getInstance()
{
    static $instance = null;

    return $instance ?: $instance = new static;
}

如果它将$instance设置为null,为什么会出现这种返回?为什么不在类的全局“空间”中创建$instance而不在getInstance中将其设置为null?

找到以下链接,这些链接对于理解单例模式非常有用


在此特定示例中,
$instance
在函数调用中以static关键字开头。这意味着变量在调用函数之间保留其状态(值)。在函数的初始调用中,无效化只发生一次。

b、 t.w.这是C处理单例的方法…

您不能使用非静态值初始化类变量,因此

class X {
    $instance = new SomeObj();
}
这是不允许的

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

static $instance = null;
将创建变量,并在第一次调用该方法时将其设置为
null
。之后,如果它被声明为
静态
,PHP将忽略该行

然后,其他代码可以如下所示:

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

为什么这是C方式?什么是PHP方式?好吧,PHP既是过程的又是面向对象的。上面是程序化的方式,在语法上非常类似于在C中的方式。看看上面的链接,它展示了所有现代的方式。这并没有解决OP关于这个具体实现的问题。