2021-03-16 17:16:50 1504次浏览 2条回答 0 悬赏 10 金钱
<?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");

最佳答案

  • yanhws 发布于 2021-03-16 20:29 举报

    因为 $instance 是静态属性 第二次 getInstance() 时候返回的还是之前的对象

    1 条回复
    回复于 2021-03-17 11:25 回复

    之前的那个对象是何时销毁呢?

  • 回答于 2021-03-17 18:39 举报

    unset($info) 只会断开和 self::$instance的引用 不会销毁对象 因为你是先赋值给self::$instance 然后 $info = self::$instance

    如果你用xdebug_debug_zval('info'); 看下的话 销毁之前refcount=2

您需要登录后才可以回答。登录 | 立即注册
YiiChina灌水总监
副总裁

YiiChina灌水总监 西藏阿里

注册时间:2019-12-25
最后登录:2022-01-26
在线时长:31小时55分
  • 粉丝6
  • 金钱6325
  • 威望0
  • 积分6635

热门问题