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