2016-03-06 39 views
1

我有一個基類叫BaseRecurring如何編寫由PHP中的子類使用的接口和基類?

它呼籲_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然後有子類實現呢?

回答

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

示例代碼嗎? –

+0

如果你注意到了,我實際上在基類中有一個完全實現的函數。我不認爲抽象類允許這樣做。或者我錯了? –

+0

抽象類不能實例化(PHP致命錯誤:'不能實例化抽象類'),但可以(通常應該)具有方法,該實現將可供兒童使用。 – Axalix