php单例与静态后期绑定

时间:2014-05-12 12:09:16

标签: php singleton

我试图理解这个Singleton实现是如何工作的。

final class UserFactory
{
    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        static $inst = null;
        if ($inst === null) {
            echo "inst was null \n";
            $inst = new UserFactory();
        }
        else {
            echo "inst was not null this time \n";
        }
        return $inst;
    }

    /**
     * Private ctor so nobody else can instance it
     *
     */
    private function __construct()
    {

    }
}

echo "get user1 \n";
$user1 = UserFactory::Instance();
echo "get user2 \n";
$user2 = UserFactory::Instance();

if ($user1 === $user2){
    echo "they are the same obj \n";
}

其中输出以下内容:

get user1 
inst was null 
get user2 
inst was not null this time 
they are the same obj 

我不明白为什么第一次将$ inst初始化为null并且$ inst === null测试通过,但后来的调用不会发生同样的情况。

1 个答案:

答案 0 :(得分:3)

这是因为$inst被声明为静态变量。如果您删除 static 关键字,那么您将获得null第二次。

来自PHP Docs..

  

静态变量仅存在于本地函数范围中,但确实如此   当程序执行离开这个范围时,不要失去它的价值