提问者:小点点

如何在PHP中编写子类使用的接口和基类?


我有一个名为baseRecurrential的基类。

它有一个名为\u checkCurrentMonth

\u checkCurrentMonth内,

baseRecurrential类中的我的代码是

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);
}

问题是我不希望基类定义check Month的实现。我希望子类实现check Month方法。

我希望有一个名为CheckMonthInterface的接口,它将显式地声明一个名为checkMonth的方法。

那么,我是否让基类实现CheckMonthInterface,然后保持该方法为空?

或者我有基类不实现CheckMonthInterface,然后让子类实现它?


共1个答案

匿名用户

这完全取决于您需要的逻辑,但通常有两种常见方式:

  • 定义一个抽象父类(把它看作一个泛型行)并添加一个抽象方法,这样非抽象子类就必须添加自己的实现
  • 定义一个接口(将其视为实现某个公共功能的契约),并将其添加到必须具有此实现的类中

这个链接也很有用:抽象类与接口

示例:

<?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)"