加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

实现PHP单例:静态类属性或静态方法变量?

发布时间:2020-12-13 13:58:34 所属栏目:PHP教程 来源:网络整理
导读:所以,我一直执行一个这样的单身人士: class Singleton { private static $_instance = null; public static function getInstance() { if (self::$_instance === null) self::$_instance = new Singleton(); return self::$_instance; } private function _
所以,我一直执行一个这样的单身人士:
class Singleton {
    private static $_instance = null;
    public static function getInstance() {
        if (self::$_instance === null) self::$_instance = new Singleton();
        return self::$_instance;
    }
    private function __construct() { }
}

然而,最近我觉得我也可以用成员静态变量实现它:

class Singleton {
    public static function getInstance() {
        //oops - can't assign expression here!
        static $instance = null; // = new Singleton();
        if ($instance === null) $instance = new Singleton();
        return $instance;
    }
    private function __construct() { }
}

对我来说,这样做比较干净,因为它不会让课堂混乱,我不需要做任何明确的存在检查,但是因为我从来没有见过这个实现,我想知道:

第一个使用第二个实现有什么问题吗?

你可能意味着稍微修改(否则我有语法错误):
<?php
class Singleton {
    public static function getInstance() {
        static $instance;
        if ($instance === null)
            $instance = new Singleton();
        xdebug_debug_zval('instance');
        return $instance;
    }
    private function __construct() { }
}
$a = Singleton::getInstance();
xdebug_debug_zval('a');
$b = Singleton::getInstance();
xdebug_debug_zval('b');

这给出:

实例:(refcount = 2,is_ref = 1),
对象(singleton)的[1]

a:(refcount = 1,is_ref = 0),
对象(singleton)的[1]

实例:(refcount = 2,
对象(singleton)的[1]

b:(refcount = 1,
对象(singleton)的[1]

所以它的缺点是每次调用都会创建一个新的zval.这不是特别严重,所以如果你喜欢,请继续.

zval分离被强制的原因是在getInstance里面,$instance是一个引用(在=& amp ;;的意义上它有引用计数2(一个用于方法中的符号,另一个用于静态存储)由于getInstance通过引用不返回,zval必须被分离 – 对于返回,创建一个新的引用计数1,引用标志清除.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读