【发布时间】:2020-02-25 20:21:43
【问题描述】:
还没有找到答案,但我确信一定有一个:当对象相互引用时,如何防止对象递归/循环?一个例子:
class Patient {
private $Issues = array();
[...]
public function __construct($id) {
[ Get data from DB ]
while ($row = $result->fetch_assoc()) {
$this->Issues[$row['idIssue']] = new Issue($row['idIssue']);
}
[...]
}
}
class Issue {
private $Patient;
[...]
public function __construct($id) {
[ Get data from DB ]
$this->Patient = new Patient($row['idPatient']); <-- Leads to recursion as the patient will load all it's Issues() etc. etc.
[...]
}
}
如何防止这种情况发生?我可以使用 Patient() 的 id 而不是真实对象,但这感觉就像是 hack。有没有办法使用实物?
【问题讨论】:
-
让
Issue构造函数采用Patient实例吗?但是,具有循环依赖关系通常被认为是一种反模式。这个问题绝对需要了解患者吗? -
谢谢,这就是下面的建议。问题不一定需要了解患者,但我有其他课程需要了解彼此。
标签: php loops object recursion reference