」を父親の属性を取得;)OOP:私は再び午前「子」オブジェクトからここ
私の問題の気圧は、例えば、ネストされた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(); //?
、すべての息子が互いからインディペンデントが、父親1から属性と値を継承しなければなりません。..
:
やろうとして何イムあるclass Son extends Father{
[....]
しかし、私は父が私は新しいson..otherwise父の属性を追加するたびにヌル
になります属性を宣言する必要があります助けが必要ですか?
サイド・コメントとして:息子を父親に広げることは概念的には分かりますが、あなたの息子は一般的に真実ではありません。妥当なのは、父と息子の両方が共通の属性を持つ親クラスPersonを作成することです。 – HerdplattenToni
私はHerdplanttenToniに同意する必要があります。オブジェクト指向の原則を適用すると、息子や父親になることができるタイプのPersonクラスが使用されます。 FatherクラスとSonクラスを使用すると、データモデルでありオブジェクトモデルではない関係につながります。 –