我正在阅读 OOP 中的模式,并发现了单例模式的这段代码:
class Singleton
{
/**
* @var Singleton reference to singleton instance
*/
private static $instance;
/**
* gets the instance via lazy initialization (created on first usage)
*
* @return self
*/
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static;
}
return static::$instance;
}
/**
* is not allowed to call from outside: private!
*
*/
private function __construct()
{
}
/**
* prevent the instance from being cloned
*
* @return void
*/
private function __clone()
{
}
/**
* prevent from being unserialized
*
* @return void
*/
private function __wakeup()
{
}
}
有问题的部分是static::$instance = new static;
。 new static
到底是做什么的或者这个例子是如何工作的。我熟悉您的普通new Object
,但不熟悉new static
。任何对 php 文档的引用都会有很大帮助。
最佳答案
基本上,这是一个可扩展的类,每当您调用 getInstance()
时,您都会获得您在其中调用它的任何类的单例(扩展此单例类)。如果您仅在一个实例中使用它,则可以对类名进行硬编码,或者如果您已在类中对此进行了硬编码,则可以使用new self
。
此外,单例被认为是一种反模式,请参阅答案以了解有关此模式的更多详细信息 why-is-singleton-considered-an-anti-pattern
关于PHP 静态关键字与 new 一起使用来构建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27734266/