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

pmm*_*pmm 4 php oop singleton

为什么这不起作用?每个实例不应该简单地互相引用一次吗?

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();
Run Code Online (Sandbox Code Playgroud)

irc*_*ell 5

你有所谓的循环依赖。A需要B完成才能构建,B需要A完成才能构建。所以它永远循环下去。

基本上,发生的情况是self::$instance每个类在完成之前都不会被填充new class()。因此,在构造函数中,您正在调用 other getInstance。但每次你击中get_instance(),self::$instance仍然为空,因为前一次new从未完成。你一圈又一圈地走。它会一直持续到最后。

相反,在构建后添加它:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我真的建议重新构建您的关系和类,以便注入依赖项而不是创建独立的单例。