나는 혼란의 일부가 물체와 물체의 집합 사이의 구별에서 왔다고 생각한다. 이 가능한 솔루션을 위해, 나는 각각의 클래스를 사용하여 함수가 콜렉션 클래스에 속할 수 있도록했다.
재귀 함수 자체는 줄 단위로 주석 처리되었으므로 충분히 명확 해지기를 바랍니다.
<?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);
어쩌면이 대답 건너 충분히 운이 좋다, 희망 당신은 지금 당신의 숙제를하고 실제로 주제를 연구.