PHP中的单例模式示例

时间:2014-10-30 07:21:04

标签: 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并且新实例将永远创造。 所以这不是一个单身人士。你能解释一下吗?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

请参阅http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

static $instance = null;

仅在第一次函数调用

上运行
  

现在,$ a仅在第一次调用函数

时初始化

以及所有其他时间它将存储创建的对象