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

时间:2016-03-06 02:07:58

标签: php inheritance interface

我有一个名为BaseRecurring的基类。

它有一个名为_checkCurrentMonth

的受保护函数

_checkCurrentMonth内,

BaseRecurring类中的代码是

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

问题在于我不希望基类定义checkMonth的实现。我希望子类实现checkMonth方法。

我打算有一个名为CheckMonthInterface的接口,它将明确声明一个名为checkMonth的方法。

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

或者我是否有基类没有实现CheckMonthInterface然后让子类实现它?

1 个答案:

答案 0 :(得分:1)

这一切都取决于你需要的逻辑,但通常有两种常见方式:

  • 定义一个抽象的父类(将其视为泛型线)并添加一个抽象方法,这样非抽象的子类就必须添加自己的实现。
  • 定义一个接口(将其视为实现常见内容的契约)并将其添加到必须具有此实现的类中。

此链接也很有用:Abstract Class vs. Interface

示例:

<?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)"
相关问题