带有静态延迟绑定的PHP单例模式


php singleton with static late binding

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

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测试通过了,但在以后的调用中却没有发生同样的情况。

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

From the PHP Docs.

静态变量只存在于局部函数作用域中,但它确实存在当程序执行离开此作用域时,不丢失其值