【发布时间】:2009-07-28 13:58:51
【问题描述】:
我又来了;)
我的问题在于嵌套的 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(); //?
所以,每个儿子都必须彼此独立,但继承父亲的属性和价值观..
我尝试过继承:
class Son extends Father{
[....]
但是我每次添加新儿子时都必须声明父亲属性..否则父亲的属性将为null
有什么帮助吗?
【问题讨论】:
-
作为旁注:让儿子扩展父亲在概念上意味着,你的儿子是父亲,这通常是不正确的。合理的做法是创建一个父类 Person ,它具有父类和子类都继承自它的公共属性。
-
我必须同意 HerdplanttenToni 的观点。应用面向对象的原则将导致使用 Person 类,该类可以是儿子或父亲。使用父类和子类导致关系是数据模型而不是对象模型。
标签: php oop class inheritance