Why does this not work? Shouldn’t each instance simply reference each other once?
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();
You have what’s known as a circular-dependency. A needs B to complete to construct, and B needs A to complete to construct. So it goes round and round forever.
Basically, what’s happening is that
self::$instanceon each class doesn’t get populated untilnew class()finishes. So in the constructor, you’re calling the othergetInstance. But every time you hitget_instance(),self::$instanceis still null because the previousnewnever finsihed. And round and round you go. It will keep going until the end.Instead, add it in after construction:
However, I would really suggest re-architecting your relationships and classes so that you Inject the Dependencies rather than making self-dependent singletons.