PHP static关键字与new一起用于构建对象

时间:2015-01-01 20:15:01

标签: php oop static

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

1 个答案:

答案 0 :(得分:2)

基本上这是一个可扩展的类,每当你调用getInstance()时,你将获得你所称的任何类的单例(扩展这个单例类)。如果您只在一个实例中使用它,则可以对类名进行硬编码,或者如果您在课堂上对其进行了硬编码,则使用new self

此外,单身人士被视为反模式,请参阅答案,了解有关此模式的更多详情why-is-singleton-considered-an-anti-pattern