OO设计:从父母那里返回子课程

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).

Jus*_*ner 5

您正在寻找的实际上是一种称为工厂模式的设计模式.你可以在这里阅读:

工厂模式

还有一些较长的PHP文章:

PHP中的设计模式PHP
中使用工厂模式的基础知识