2009-07-28 73 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方法中的儿子,我早就该方法需要一个已经创建的儿子作为其参数。