【问题标题】:How to write interface and base class to be used by the child class in PHP?如何在 PHP 中编写子类使用的接口和基类?
【发布时间】:2016-06-19 17:38:13
【问题描述】:

我有一个名为 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,然后让子类实现它?

【问题讨论】:

    标签: php inheritance interface


    【解决方案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)"
    

    【讨论】:

    • 如果你注意到了,我实际上在基类中有一个完全实现的函数。我不认为抽象类允许这样做。还是我错了?
    • 抽象类不能被实例化(PHP 致命错误:Cannot instantiate abstract class),但可以(通常应该)有方法,这些方法可供孩子使用。
    猜你喜欢
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2014-09-17
    • 2023-03-08
    • 2020-07-15
    • 2016-04-14
    • 2012-05-01
    相关资源
    最近更新 更多