我有一个主引导类(示例中的singleton1)实例化一些单例类.在那些单例类中,我需要保留对app主类的引用,以便于快速引用它,但这样做给了我一个:
Fatal error: Maximum function nesting level of '100' reached, aborting
这是exmaple代码:
<?php
class Singleton1 {
private static $instance;
private function __construct() {
Singleton2::instance();
}
public static function instance () {
if( !self::$instance ) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public function test () {
echo 'Good.';
}
private function __clone() { }
private function __wakeup() { }
}
class Singleton2 {
private static $instance;
private $singleton1;
private function __construct() {
$this->singleton1 = Singleton1::instance();
}
public static function instance () {
if( !self::$instance ) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public function test () {
$this->singleton1->test();
}
private function __clone() { }
private function __wakeup() { }
}
Singleton1::instance();
Singleton2::instance()->test();
我找不到任何合理的解释来解决这个问题……
谢谢.
解决方法:
您的代码具有以下循环:
Singleton2::__construct()
Singleton1::instance()
Singleton1::__construct()
Singleton2::instance()
Singleton2::__construct()