2009-07-28 83 views
0

在這裏我再次找回「父親」屬性;)OOP:從「子」對象

我的問題ATM是嵌套的PHP類,我有,例如,像這樣的一類:

class Father{ 
    public $father_id; 
    public $name; 
    public $job; 
    public $sons; 
    public function __construct($id, $name, $job){ 
     $this->father_id = $id; 
     $this->name = $name; 
     $this->job = $job; 
     $this->sons = array(); 
    } 

    public function AddSon($son_id, $son_name, $son_age){ 
     $sonHandler = new Son($son_id, $son_name, $son_age); 
     $this->sons[] = $sonHandler; 
     return $sonHandler; 
    } 

    public function ChangeJob($newJob){ 
     $this->job = $newJob; 
    } 
} 

class Son{ 
    public $son_id; 
    public $son_name; 
    public $son_age; 
    public function __construct($son_id, $son_name, $son_age){ 
     $this->son_id = $son_id; 
     $this->son_name = $son_name; 
     $this->son_age = $son_age; 
    } 
    public function GetFatherJob(){ 
     //how can i retrieve the $daddy->job value?? 
    } 
} 

就是這樣,一個無用的類來解釋我的問題。 什麼即時試圖做的是:

$daddy = new Father('1', 'Foo', 'Bar'); 
//then, add as many sons as i need: 
$first_son = $daddy->AddSon('2', 'John', '13'); 
$second_son = $daddy->AddSon('3', 'Rambo', '18'); 
//and i can get here with no trouble. but now, lets say i need 
//to retrieve the daddy's job referencing any of his sons... how? 
echo $first_son->GetFatherJob(); //? 

所以,每次兒子必須彼此indipendent但繼承了父親一個屬性和值..

我和繼承tryed:

class Son extends Father{ 
[....] 

但我將不得不宣佈父親的屬性我每次添加一個新的son..otherwise父親的屬性時會

有什麼幫助嗎?

+3

作爲一個方面的評論:讓子延伸父親會在概念上表示,你的兒子是一個父親,這通常是不正確的。但是,合理的做法是創建一個父類,與父類和子都具有共同屬性的人都從中繼承。 – HerdplattenToni 2009-07-28 14:33:52

+0

我必須同意HerdplanttenToni。應用面向對象的原則將導致使用一個Person類,這個類可以是一個兒子或父親。使用Father類和Son類引發了一種數據模型而不是對象模型的關係。 – 2014-12-11 12:53:15

回答

3

除非你告訴兒子他們的父親是誰,否則你不能。這可以通過向兒子添加setFather()方法並調用父親的addSon()方法來完成。

例如。

class Son { 
    protected $_father; 
    // ... 
    public function setFather($father) { 
     $this->_father = $father; 
    } 

    public function getFather() { 
     return $this->_father; 
    } 
} 

class Father { 
    // ... 
    public function AddSon($son_id, $son_name, $son_age){ 
     $sonHandler = new Son($son_id, $son_name, $son_age); 
     $sonHandler->setFather($this); 
     $this->sons[] = $sonHandler; 
     return $sonHandler; 
    } 
} 

作爲一個方面說明,我不會創建AddSon方法中的兒子,我早就該方法需要一個已經創建的兒子作爲其參數。