我正在阅读有关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
则使用类名。
请参阅答案她以获取有关此模式的更多详细信息,为什么单例被认为是反模式