我在PHP中有一個我想克隆的面向對象的父子樹。 困難的部分是,進入樹並不總是通過根,但有時通過根的孩子,像這樣:在PHP中克隆父子樹,從子開始,避免無窮遞歸
[Root]
-- [Element1] START CLONE
-- [Element3]
-- [Element4]
-- [Element2]
-- [Element5]
所以我想要做的是克隆整個樹,通過調用$new = clone $element1;
__clone()方法指出,每個孩子也必須被克隆,並且,如果所示的情況發生*,父母也必須克隆。
* Root在Element1中顯式設置爲父級,因此係統可以識別這種情況並對其進行操作。
問題是,從Element1開始clone
操作,Root也必須被克隆。 Root的克隆過程規定必須克隆所有子元素,因此Element1的clone
操作再次被調用,然後重複相同的克隆過程,產生無限循環。
此外,根不包含Element1的第一個克隆,但它將生成自己的克隆以作爲子項添加。然後Element1將具有Root作爲其父項,但Root將不具有與小孩相同的Element1。
我希望我以清晰的方式提出問題,並且有人可以幫助我找到解決方案。
編輯:
最終的解決方案:
/**
* The $replace and $with arguments allow a custom cloning procedure. Instead of
* being cloned, the original child $replace will be replaced by $with.
*/
public function duplicate($replace = null, $with = null) {
// Basic cloning
$clone = clone $this;
// If parent is set
if(isset($this->parent)) {
// Clone parent, replace this element by its clone
$parentClone = $this->parent->duplicate($this, $clone);
$clone->parent = $parentClone;
}
// Remove all children in the clone
$clone->clear();
// Add cloned children from original to clone
foreach($this->getChildren() as $child) {
if($child === $replace)
// If cloning was initiated from this child, replace with given clone
$childClone = $with;
else
// Else duplicate child normally
$childClone = $child->duplicate();
// Add cloned child to this clone
$clone->add($childClone);
}
return $clone;
}
你使用什麼數據結構?有父母子女屬性的對象?陣列? – deceze
我正在使用數組來列出對象的所有子項。在描述的情況下,Element1也有一個「父」屬性。 – RemiX