How to write interface and base class to be used by the child class in PHP?
我有一个名为
它有一个名为
在
我在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | protected function _checkNextMonth($type, $startDate = 1, $endDate = 1) { $incrementToFirstDay = $startDate - 1; $incrementToLastDay = $endDate - 1; $startDate = new \DateTime('first day of this month'); $endDate = new \DateTime('first day of next month'); if ($incrementToFirstDay > 0 || $incrementToLastDay > 0) { // e.g. if we want to start on the 23rd of the month // we get P22D $incrementToFirstDay = sprintf('P%dD', $incrementToFirstDay); $incrementToLastDay = sprintf('P%dD', $incrementToLastDay); $startDate->add(new \DateInterval($incrementToFirstDay)); $endDate->add(new \DateInterval($incrementToLastDay)); } $this->checkMonth($type, $startDate, $endDate); } |
问题是我不希望基类为
我打算有一个名为
那么,我是否让基类实现
或者让基类不实现
这完全取决于您需要的逻辑,但通常有两种常见的方法:
- 定义一个抽象父类(像一个泛型行一样考虑它)并添加一个抽象方法,这样非抽象子类就必须添加自己的实现。
- 定义一个接口(把它想象成一个实现公共事物的契约),并将它添加到那些必须具有此实现的类中。
这个链接也很有用:抽象类与接口
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php abstract class Polygon { protected $name; abstract public function getDefinition(); public function getName() { return $this->name; } } class Square extends Polygon { protected $name = 'Square'; public function getDefinition() { return $this->getName() . ' is a regular quadrilateral, which means that it has four equal sides and four equal angles (90-degree angles, or right angles).'; } } class Pentagon extends Polygon { protected $name = 'Pentagon'; } echo (new Square())->getDefinition(); // Square is a regular quadrilateral, which means that it has four equal sides and four equal angles (90-degree angles, or right angles). echo (new Pentagon())->getDefinition(); // PHP Fatal error:"class Pentagon contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Polygon::getDefinition)" |