php - PHP 中的单例模式示例

标签 php oop design-patterns singleton

我是 PHP 新手。 这是根据 phptherightway.com 的标准单例模式示例:

<?php
class Singleton
{
    public static function getInstance()
    {
        static $instance = null;
        if (null === $instance) {
            $instance = new static();
        }

        return $instance;
    }

    protected function __construct()
    {
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }
}

class SingletonChild extends Singleton
{
}

$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());             // bool(true)

$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance());      // bool(false)

var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)

问题在这一行:

        static $instance = null;
        if (null === $instance) {
            $instance = new static();
        }

据我所知,if (null === $instance) 始终为 TRUE,因为每次我调用方法 getInstance() 时,变量 $instance 总是被设置为 null 并且总是会创建一个新实例。 所以这不是真正的单例。你能解释一下吗?

最佳答案

在此处查看“示例 #5 静态变量的使用示例”: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

“现在,$a 仅在第一次调用函数时初始化,每次调用 test() 函数时,它都会打印 $a 的值并递增它。”

关于php - PHP 中的单例模式示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647184/

相关文章:

php - 为 MYSQL 格式化时间 12 小时制

php - 如何在 PHP 中创建搜索过滤器?

php - 即使条件为 false,其他部分也不会执行 Laravel 5.2

c# - 奇怪的继承修改

c - 处理中断数据的设计模式

php - mysqli 从不返回任何东西

java - Cassandra 用 Ja​​va 从文件中保存数据

c# - 公共(public)引用应该如何在程序集中传递?

php - 寻找加载器设计模式

android - 使用 ViewModel 的接口(interface)?