我正在用php编写一些实体类,这些类可能与存储库类相互指向(以避免使用本地实体存储库查询过多的数据库):
class Foo
{
public $fooId;
public $bar;
function __construct($entity_id)
{
/**
* Some Database stuff to get Foo object based on $entity_id
**/
$this->bar = Repository::get('Bar', $databaseStuff->barId);
}
}
class Bar
{
public $foo;
function __construct($entity_id)
{
/**
* Some Database stuff to get Bar object based on $entity_id
**/
$this->bar = Repository::get('Bar', $databaseStuff->barId);
}
}
class Repository
{
private static $entities = [];
/**
* @param string $entity_name
* @param int $entity_id
* @return mixed
*/
public static function &get($entity_name, $entity_id)
{
$entity_name = ucfirst(strtolower($entity_name));
if(!isset(self::$entities[$entity_name][$entity_id]))
{
self::$entities[$entity_name][$entity_id] =& $entity_name($entity_id);
}
return self::$entities[$entity_name][$entity_id];
}
}
$foo = new Foo(1337);问题是,我得到了某种超时/堆栈溢出,这可能是因为$foo->bar是对Bar对象的引用,而$bar->foo是对Foo对象的引用,等等……
在我的代码中(或者在我的逻辑中)会有什么问题呢?谢谢。
发布于 2015-07-18 10:22:54
如果我认为正确的话,Bar的构造函数将尝试创建新的Bar。
我想这种嵌套的构造永远不会结束。这是相同的,例如,当一个函数递归地调用自己而没有退出的时候。
脚本甚至不会编写到存储库中。
试过x调试吗?这可能很快就会显示出问题。
顺便说一句,有可能是不好的复制/粘贴。Foo类中的注释与使用它的行不匹配。在类栏中设置$this-> Bar,但只声明类变量$foo。
https://stackoverflow.com/questions/31364150
复制相似问题