【问题标题】:PHP static keyword used with new in building an object在构建对象时与 new 一起使用的 PHP 静态关键字
【发布时间】:2015-01-01 20:15:00
【问题描述】:

我正在阅读有关 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 文档的引用都会有很大帮助。

【问题讨论】:

标签: php oop static


【解决方案1】:

基本上这是一个可扩展的类,每当你调用getInstance() 时,你都会得到一个你调用它的类的单例(扩展这个单例类)。如果你只在一个实例中使用它,你可以硬编码类名,或者如果你在你的类中硬编码了它,则使用new self。

此外,单例被视为反模式,有关此模式的更多详细信息,请参阅她的答案why-is-singleton-considered-an-anti-pattern

【讨论】:

  • 感谢单身人士的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多