Php OO设计:从父类返回子类
说到多态性,我还是个新手,所以我希望我能正确地表达我的问题 假设我的数据库中有表——狗、猫和老鼠。我希望能够调用类似以下内容:Php OO设计:从父类返回子类,php,oop,polymorphism,Php,Oop,Polymorphism,说到多态性,我还是个新手,所以我希望我能正确地表达我的问题 假设我的数据库中有表——狗、猫和老鼠。我希望能够调用类似以下内容: $animal = new Animal("dog", 12); class Animal { protected $id; protected $legs; protected $height; function __construct($type, $id) { if ($type == "dog") { return new
$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;
}
}
动物类是这样的:
$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工厂模式实现”您所寻找的实际上是一种称为工厂模式的设计模式。你可以在这里阅读: 还有一些关于PHP的较长文章:
您需要的是“工厂模式”。与其直接创建新的
Animal
s,不如调用选择要创建的动物类型的函数。在Java中,我可能会将其作为类的静态方法,在Python中,我会将所有动物类存储在链接到键的字典中,这样我就可以查找键,然后将参数传递给构造函数
对于PHP,我在上找到了一篇文章。是的!就是这样。我发现“PHP中的设计模式”最有帮助。另一篇PHP文章对我来说有点困惑,因为它同时讨论了抽象。