[英]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.