簡體   English   中英

如何在PHP中編寫子類使用的接口和基類?

[英]How to write interface and base class to be used by the child class in PHP?

我有一個名為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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM