2013-03-07 44 views
0

圖片我想擁有一個對象$ parent;作爲屬性的PHP對象

其中,例如:

$parent->firstname = "Firstname"; 
    $parent->lastname = "Lastname"; 
    $parent->children = ??? 

- >這則必須是對象的集合,這樣以後我可以這樣做:

foreach ($parent->children as $child) { 
     $child->firstname 
     $child->lastname 
    } 

這是可能的事是什麼?

+3

'$ parent-> children'應該是_array_對象。孩子們從哪裏來?這會影響你初始化數組的方式。 – 2013-03-07 13:57:13

+0

你真的應該使用getter和setter方法。不直接將值存儲到屬性。 – 2013-03-07 14:00:16

+1

請參閱:[PHP中的類內對象數組](http://stackoverflow.com/questions/7812198/array-of-objects-within-class-in-php) – hakre 2013-03-07 14:01:29

回答

0

是可能的,例如,如果你讓孩子array

這僅僅是例子,這不是最好的解決辦法:

class person 
{ 
    public $firstname = 'Jane'; 
    public $lastname = 'Doe'; 
    public $children = array(); 
} 

$parent = new person(); 
$parent->firstname = "Firstname"; 
$parent->lastname = "Lastname"; 

//1st child 
$child = new person(); 
$child->firstname = 'aa'; 
$parent->children[] = $child; 

//2nd child 
$child = new person(); 
$child->firstname = 'bb'; 
$parent->children[] = $child;   

foreach ($parent->children as $child) { 
    ... 
} 
0

這取決於一點你想要什麼。由於你的類型只是屬性對象,我認爲Vahe Shadunts的解決方案是最輕量級和最簡單的。

如果你想在PHP中獲得更多的控制權,你需要使用getter和setter。這將使您可以使其更具體。

至於foreachDocs而言,所有的子對象需要做的是落實IteratorIteratorAggregate接口,它可以再裏面foreach使用(見Object IterationDocs)。

下面是一個例子:

$jane = ConcretePerson::build('Jane', 'Lovelock'); 

$janesChildren = $jane->getChildren(); 
$janesChildren->attachPerson(ConcretePerson::build('Clara')); 
$janesChildren->attachPerson(ConcretePerson::build('Alexis')); 
$janesChildren->attachPerson(ConcretePerson::build('Peter')); 
$janesChildren->attachPerson(ConcretePerson::build('Shanti')); 

printf(
    "%s %s has the following children (%d):\n", 
    $jane->getFirstname(), 
    $jane->getLastname(), 
    count($jane->getChildren()) 
); 

foreach($janesChildren as $oneOfJanesChildren) 
{ 
    echo ' - ', $oneOfJanesChildren->getFirstname(), "\n"; 
} 

輸出:

Jane Lovelock has the following children (4): 
- Clara 
- Alexis 
- Peter 
- Shanti 

,在這裏的後臺工作,這些命名的接口和對象(我在最後的代碼鏈接)有一定的好處相比,只需要數組和屬性(如果需要更多功能)(例如,隨着時間的推移)。

比方說,珍結婚與珍妮特所以他們都共享同一個孩子,讓雙方分享:

$janet = ConcretePerson::build('Janet', 'Peach'); 
$janet->setChildren($janesChildren); 

現在,珍妮特得到一個新的子:

$janet->getChildren()->attachPerson(ConcretePerson::build('Feli')); 

而且會自動完成簡,因爲兩者共享相同的兒童對象。

但是PHP對於這些類型集合並不是很強大,因此您有相當多的樣板代碼來完成這些工作。

code gist