谁一开始就是大神?

请问一下各位这个为啥输出还是helloworld?[2.0]

<?php
class AppInfo
{
    private $props = array();

    private static $instance;

    //防止外界实例化对象
    private function __construct()
    {
    }
    //防止外界clone实例
    private function __clone()
    {
    }

    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public function setProperty($key, $val)
    {
        $this->props[$key] = $val;
    }

    public function getProperty($key)
    {
        return $this->props[$key];
    }
}

$info = AppInfo::getInstance();
$info->setProperty("name","hello world");
unset($info);
$info2 = AppInfo::getInstance();
echo $info2->getProperty("name");

因为 $instance 是静态属性 第二次 getInstance() 时候返回的还是之前的对象
unset($info) 只会断开和 self::$instance的引用 不会销毁对象 因为你是先赋值给self::$instance 然后 $info = self::$instance
如果你用xdebug_debug_zval(‘info’); 看下的话 销毁之前refcount=2

赞(0) 打赏
未经允许不得转载:菜鸟之家 » 请问一下各位这个为啥输出还是helloworld?[2.0]

评论 抢沙发

登录

找回密码

注册