我有一个名为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
,然后让子类实现它?
这完全取决于您需要的逻辑,但通常有两种常见方式:
这个链接也很有用:抽象类与接口
示例:
<?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)"