親クラスProduct
と 2 つの子クラスがあります:Toothbrush
とChainsaw
. 以下に示すように設定されています。
親クラスは次のとおりです。
class Product {
protected $productid;
protected $type;
public function __construct( $productid ) {
$this->productid = $productid;
// Performs a lookup in the database and then populates the $type property
}
}
..そしてここに子供たちがいます:
class Toothbrush extends Product {
public function getPrice() {
return 5; // returning an integer for simplicity; there's a calculation going on here
}
}
class Chainsaw extends Product {
public function getPrice() {
return 1000; // in USD
}
}
のリストを繰り返し処理し、アイテムが であるかes$productid
であるかに関係なく、アイテムの対応する価格を取得したいと考えています。chainsaw
toothbrush
問題(それか?)
今、親クラスは機能を実装するために子クラスに依存すべきではないということを何度も聞いてきました(はい、この質問を他の多くの質問と一緒に読んでいます)。
これが、現在使用しているソリューション (以下) が最適ではないと考えるようになった理由です。
class Product {
...
public function getPrice() {
switch($this->type) {
case 'toothbrush':
$theproduct=new Toothbrush($this->productid);
return $theproduct->getPrice();
break;
case 'chainsaw':
$theproduct=new Chainsaw($this->productid);
return $theproduct->getPrice();
break;
}
}
}
ここで何かが手抜きされていることは明らかです (30 種類の製品を入手したらどうなるかを考えると身震いします)。抽象化、インターフェイス、および継承について読んだことがありますが、このシナリオでどれが機能するかわかりません。
ありがとうございました!
編集
たくさんの答えを見ていますが、まだそれを釘付けにしたものはありません. 要点は次のとおりです
。productid しかない場合、子メソッドを呼び出すにはどうすればよいですか? (上記のシナリオでは、Product
クラスはコンストラクターでデータベースから型を取得し、$type
それに応じてプロパティを設定します。