我有一个父类Product
和两个子类: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
}
}
我想遍历$productid
's 列表并获得项目的相应价格,无论它们是chainsaw
's 还是toothbrush
es。
问题(或者是吗?)
现在我一遍又一遍地听到父类不应该依赖子类来实现功能(是的,我读过这个问题,以及其他许多问题)。
这就是为什么我被引导认为我目前使用的解决方案(如下)不是最佳的:
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
属性。