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父亲的属性时会空
有什么帮助吗?
作为一个方面的评论:让子延伸父亲会在概念上表示,你的儿子是一个父亲,这通常是不正确的。但是,合理的做法是创建一个父类,与父类和子都具有共同属性的人都从中继承。 – HerdplattenToni 2009-07-28 14:33:52
我必须同意HerdplanttenToni。应用面向对象的原则将导致使用一个Person类,这个类可以是一个儿子或父亲。使用Father类和Son类引发了一种数据模型而不是对象模型的关系。 – 2014-12-11 12:53:15