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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了实现PHP单例:静态类属性或静态方法变量?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
所以,我一直执行一个这样的单身人士:
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; amp ;;的意义上它有引用计数2(一个用于方法中的符号,另一个用于静态存储)由于getInstance通过引用不返回,zval必须被分离 – 对于返回,创建一个新的引用计数1,引用标志清除.

脚本宝典总结

以上是脚本宝典为你收集整理的实现PHP单例:静态类属性或静态方法变量?全部内容,希望文章能够帮你解决实现PHP单例:静态类属性或静态方法变量?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。