2011-03-31 89 views
5

兩個接口這不起作用:無法實現具有相同的方法名

interface TestInterface 
{ 
    public function testMethod(); 
} 

interface TestInterface2 
{ 
    public function testMethod(); 
} 

class TestClass implements TestInterface, TestInterface2 
{ 

} 

給我的錯誤:

Fatal error: Can't inherit abstract function TestInterface2::testMethod() (previously declared abstract in TestInterface).

是正確的嗎?爲什麼這是不允許的?對我來說沒有意義。

這也會出現在抽象函數中,例如,如果您實現了一個接口,然後從具有相同名稱的抽象函數的類繼承。

回答

8

實現包含具有相同簽名的方法的兩個接口是沒有意義的。

編譯器無法知道這些方法是否實際上具有相同的目的 - 如果不是這樣,這意味着您的類中至少有一個接口不能被實現。

例子:

interface IProgram { function execute($what); /* executes the given program */ } 
interface ISQLQuery { function execute($what); /* executes the given sql query */ } 

class PureAwesomeness implements IProgram, ISQLQuery { 
    public function execute($what) { /* execute something.. but what?! */ } 
} 

所以你看,這是不可能實現的兩個接口的方法 - 這也將會是無法調用它實際上實現了從給定的接口方法的方法。

+5

但接口的全部意義在於它們沒有實現。如果你想讓你的類可以傳遞給一個爲參數指定一個接口的函數,另一個接口指定另一個接口,但都有一個共同的方法?像「getName()」這樣的方法名稱在另一個接口上不會有不同的用途。 – Gnuffo1 2011-03-31 09:20:41

+5

在這種情況下,您應該創建一個新的界面,例如'INamed'只包含'getName()'方法。 – ThiefMaster 2011-03-31 09:24:02

+1

他們沒有實現,但他們確實有語義,至少隱含。雖然你可以在一個接口中實現一個方法,在使用它的不同類中具有完全不同的含義,但這與接口的精神相反。但是,如果實現兩個不同的接口,則不能保證它們的說明符知道對方的任何內容,因此名稱相似的方法具有相似的語義。我想你可以讓每個接口擴展一個包含常用方法的通用接口。 – 2011-03-31 09:27:53

-1

這是不允許的,因爲PHP不能確定哪個接口有你想要的方法。在你的情況下,它們是相同的,但想象一下如果它們有不同的參數。

您應該重新考慮您的應用程序設計。

7

The PHP manual明確地說:

Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

+0

我不明白歧義在哪裏,因爲沒有實現(這是接口的全部要點)。我可以明白爲什麼你不想用不同簽名的相同方法,但是,在簽名相同的情況下,這不應該留給具體實現來處理嗎?例如,Java的工作方式不是這樣嗎? – Muc 2012-12-17 15:49:21

+1

我認爲你所說的有一個論點:這是一個語言設計師需要從多大程度上保護你自己的決定。沒有_intrinsic_不明確性,但是如果接口具有相同簽名的函數,它們需要的函數的語義可能匹配,或者它們可能完全不同。 – 2012-12-18 15:35:58

+0

這看起來倒退了。不應該只允許他們有不同的簽名?如果這兩種方法具有不同的簽名,則任何調用其中一種方法的人都會顯式調用他們想要的特定方法。即使這兩種方法有兩個完全不同的目標,也沒關係,因爲會調用正確的方法。但是,如果這兩種方法具有相同的簽名,並且每種方法的目標完全不同,那麼就沒有辦法可以有一種方法可以用於兩種目的,所以單一方法就沒有意義。任何人都可以提供一些計數器原理? – 2015-09-02 22:53:42

3
interface BaseInterface 
{ 
    public function testMethod(); 
} 

interface TestInterface extends BaseInterface 
{ 
} 

interface TestInterface2 extends BaseInterface 
{ 
} 

class TestClass implements TestInterface, TestInterface2 
{ 
    public function testMethod() 
    { 
    } 
} 
相關問題