PHP 静态关键字与 new 一起使用来构建对象

标签 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 文档的引用都会有很大帮助。

最佳答案

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

此外,单例被认为是一种反模式,请参阅答案以了解有关此模式的更多详细信息 why-is-singleton-considered-an-anti-pattern

关于PHP 静态关键字与 new 一起使用来构建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27734266/

相关文章:

php - 为什么密码散列,例如php 的 password_hash 这么慢?

java - 这就是您在服务层中调用 Dao 的方式吗?

java - 在类中使用共享服务

java - 非静态日志能说得过去吗?

java - SONAR 提示 Make the enclosure method "static"or remove this set

php - Cron 不会运行 Laravel 计划的作业

php - 上传多个文件php和mysql

php - 使用 PHP 提供私有(private)图像

c# - 需要一些关于引用类型的说明

python - 在python中实例化一个类时返回另一个类