2013-10-02 33 views
7

我有接口:PHP - 接口繼承 - 聲明必須是兼容

interface AbstractMapper 
{ 
    public function objectToArray(ActiveRecordBase $object); 
} 

和類:

class ActiveRecordBase 
{ 
    ... 
} 

class Product extends ActiveRecordBase 
{ 
    ... 
} 

========

但我可以」 t這樣做:

interface ExactMapper implements AbstractMapper 
{ 
    public function objectToArray(Product $object); 
} 

or this:

interface ExactMapper extends AbstractMapper 
{ 
    public function objectToArray(Product $object); 
} 

我有錯誤「聲明必須是兼容

那麼,有沒有辦法在PHP中做到這一點?

+1

我知道這是一個幾年前發佈,但現在這裏是我的兩個cents- 此錯誤消息是不這樣做與接口繼承。這個錯誤是因爲PHP不支持真正的函數/方法重載,就像在你可能對使用其他語言(例如,Java,C++)。 – anotheruser1488182

回答

10

沒有,接口必須實現準確。如果將實現限制爲更具體的子類,則它不是相同的接口/簽名。 PHP沒有泛型或類似的機制。

您可以隨時手動檢查代碼,當然:

if (!($object instanceof Product)) { 
    throw new InvalidArgumentException; 
} 
+0

但我嘗試創建另一個界面,基於此。不執行,而是繼承限制。 – violarium

+0

這並不重要,你是否擴展或實現。您無法更改界面聲明,句點。當Bar的實現比Foo指定的實現更受限制時,你不能說Foo實現Bar。 – deceze

-3
interface iInvokable { 
    function __invoke($arg = null); 
} 

interface iResponder extends iInvokable { 
    /** Bind next responder */ 
    function then(iInvokable $responder); 
} 

class Responder implements iResponder { 

    function __invoke($arg = null) 
    { 
     // TODO: Implement __invoke() method. 
    } 

    /** Bind next responder */ 
    function then(iInvokable $responder) 
    { 
     // TODO: Implement then() method. 
    } 
} 

class OtherResponder implements iResponder { 

    function __invoke($arg = null) 
    { 
     // TODO: Implement __invoke() method. 
    } 

    /** Bind next responder */ 
    function then(iInvokable $responder) 
    { 
     // TODO: Implement then() method. 
    } 
} 

class Invokable implements iInvokable { 

    function __invoke($arg = null) 
    { 
     // TODO: Implement __invoke() method. 
    } 
} 

$responder = new Responder(); 
$responder->then(new OtherResponder()); 
$responder->then(new Invokable());