我仍然是一個新手,當涉及到多態性,所以我希望我能正確地說我的問題。OO設計:從父母返回一個孩子班
比方說,我有我的數據庫中的表 - 狗,貓和鼠標。我希望能夠調用是這樣的:
$animal = new Animal("dog", 12);
與動物類是這樣的:
class Animal {
protected $id;
protected $legs;
protected $height;
function __construct($type, $id) {
if ($type == "dog") {
return new Dog($id);
}
}
}
class Dog extends Animal {
function __construct($id) {
$this->id = $id;
$this->legs = 4;
$this->height = 1;
}
}
這並不工作,但我希望能夠調用一個新的動物和通在特定的動物中,並將其退回。我怎麼設計這個? (我使用PHP)。
是的!這就是它。我發現「PHP中的設計模式」最有用。另一篇PHP文章對我來說有點混亂,因爲它同時談到了Abstraction。 – 2009-06-03 21:29:43