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

php – 2个单例类可以互相引用吗?

发布时间:2020-12-13 21:40:13 所属栏目:PHP教程 来源:网络整理
导读:为什么这不起作用?每个实例不应该只引用一次吗? class foo { private static $instance; private function __construct() { $test = bar::get_instance(); } public static function get_instance() { if (empty(self::$instance)) { self::$instance = ne
为什么这不起作用?每个实例不应该只引用一次吗?

class foo {
    private static $instance;
    private function __construct() {
    $test = bar::get_instance();
    }

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

class bar {
    private static $instance;
    public function __construct() {
    $test = foo::get_instance();
    }

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

$test = foo::get_instance();

解决方法

你有一个所谓的 circular-dependency.需要B来完成构建,而B需要A才能完成构建.所以它永远是圆形的.

基本上,正在发生的事情是每个类的self :: $实例在新的class()完成之前不会被填充.所以在构造函数中,你正在调用另一个getInstance.但是每次你点击get_instance()时,self :: $instance仍然是null,因为之前的new永远不会finsihed.你走了一圈又一圈.它会一直持续到最后.

相反,在构造之后添加它:

class foo {
    private static $instance;
    private function __construct() {
    }
    private function setBar(bar $bar) {
        $this->bar = $bar;
    }

    public static function get_instance() {
        if (empty(self::$instance)) {
            self::$instance = new foo();
            self::$instance->setBar(bar::get_instance());
        }
        return self::$instance;
    }
}

class bar {
    private static $instance;
    public function __construct() {
    }
    private function setFoo(foo $foo) {
        $this->foo = $foo;
    }
    public static function get_instance() {
        if (empty(self::$instance)) {
            self::$instance = new bar();
            self::$instance->setFoo(foo::get_instance());
        }
        return self::$instance;
    }
}

但是,我真的建议你重新设计自己的关系和课程,这样你就可以Inject the Dependencies而不是制作自立的单身人士.

(编辑:李大同)

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

    推荐文章
      热点阅读