【问题标题】:Singleton pattern example in PHPPHP中的单例模式示例
【发布时间】:2014-12-26 03:37:26
【问题描述】:

我是 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,并且总是会创建一个新实例。 所以这不是一个真正的单例。你能解释一下吗?

【问题讨论】:

标签: php oop design-patterns singleton


【解决方案1】:

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

static $instance = null;

只会在第一次调用函数时运行

现在,$a 只在第一次调用函数时被初始化

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多