キーボード、Tシャツ、コーラのボトルの3つのアイテムがあるとしましょう。
$keyboard = new Item("Keyboard");
echo $keyboard->getPrice(); // return 50;
$tshirt = new Item("Tshirt");
echo $tshirt->getPrice(); // return 20;
$cola = new Item("Cola");
echo $cola->getPrice(); // return 0 or 2 whether the bottle is empty or not.
Price
コーラのボトルを入手するためのベストプラクティスは何ですか?
私は2つのクラスを作成することから始めました:
Class Item {
$this->price;
function __construct($name) {
// ...
}
public function getPrice() {
return $this->price;
}
}
Class Bottle extends Item {
$this->empty;
function __construct($name) {
// get from database the value of $this->empty
}
public function getPrice() {
if($this->empty)
return 0;
else
return $this->price;
}
}
しかし今、私は疑問に思っています; :を使用すると、オブジェクトではなくオブジェクトを$cola = new Item("Cola");
インスタンス化しています。これは、それが「通常の」アイテムなのかボトルなのかまだわからないためです。Item
Bottle
代わりに、Bottleオブジェクトをインスタンス化して、アプリケーション内の別のロジックを調査する必要がありますか?または、アイテムオブジェクトを「再作成」して、ボトルとして変換する方法はありますか?