Mat*_*ick 0 php oop polymorphism
在多态性方面,我仍然是新手,所以我希望我能正确地说出我的问题.
假设我的数据库中有表格 - 狗,猫和鼠标.我想能够打电话给:
$animal = new Animal("dog", 12);
Run Code Online (Sandbox Code Playgroud)
动物类是这样的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,但我希望能够调用一个新的动物并传递特定的动物并让它返回.我该如何设计呢?(我正在使用PHP).