我认为一些混淆可能来自对象和对象集合之间的区别。为了这个可能的解决方案,我为每个类使用了一个类,以便函数可以属于集合类。
递归函数本身是逐行注释的,所以我希望它很清楚。
<?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);
希望你现在做你的功课,其实研究这个问题,所以也许你足够幸运地遇到这个答案。