我認爲一些混淆可能來自對象和對象集合之間的區別。爲了這個可能的解決方案,我爲每個類使用了一個類,以便函數可以屬於集合類。
遞歸函數本身是逐行註釋的,所以我希望它很清楚。
<?php
class related_object {
public $ID;
public $Name;
public $ParentID;
public function __construct($id, $name, $parent=0) {
$this->ID = $id;
$this->Name = $name;
$this->ParentID = $parent;
}
}
class related_object_library {
public $objects;
public function add($object) {
$this->objects []= $object;
}
public function addressPath($id, $path='') {
// iterate through each object in collection
foreach ($this->objects as $object){
// if ID matches, then return Name
if ($object->ID === $id) {
$path = $object->Name.$path;
// if it has a parent, then recurse, else just return
if (!empty($object->ParentID))
return $this->addressPath($object->ParentID,"->$path");
else return $path;
} // end if match
} // end loop
} // end function
} // end class
$collection = new related_object_library();
$collection->add(new related_object(1,'Egypt'));
$collection->add(new related_object(2,'USA'));
$collection->add(new related_object(3,'Giza',1));
$collection->add(new related_object(4,'6th october',3));
echo $collection->addressPath(4);
希望你現在做你的功課,其實研究這個問題,所以也許你足夠幸運地遇到這個答案。