无法实现具有相同方法名称的两个接口

时间:2011-03-31 09:17:05

标签: php oop interface

这不起作用:

interface TestInterface
{
    public function testMethod();
}

interface TestInterface2
{
    public function testMethod();
}

class TestClass implements TestInterface, TestInterface2
{

}

给我错误:

  

致命错误:无法继承抽象函数TestInterface2 :: testMethod()(之前在TestInterface中声明为abstract)。

这是对的吗?为什么不允许这样做?对我没有意义。

这也适用于抽象函数,例如,如果您实现一个接口,然后从具有相同名称的抽象函数的类继承。

5 个答案:

答案 0 :(得分:11)

看来当前的PHP版本实际上可以做到这一点。我已跟踪此行为的行为变化:

https://github.com/php/php-src/commit/31ef559712dae57046b6377f07634ad57f9d88cf#Zend/zend_compile.c

从php-5.3.9开始,记录的行为似乎已经改变了。

答案 1 :(得分:9)

The PHP manual明确说明:

  

在PHP 5.3.9之前,类无法实现两个指定具有相同名称的方法的接口,因为它会导致歧义。只要重复方法具有相同的签名,更新版本的PHP就允许这样做。

答案 2 :(得分:7)

实现包含具有相同签名的方法的两个接口是没有意义的。

编译器无法知道方法是否实际具有相同的目的 - 如果不是,则意味着至少有一个接口不能由您的类实现。

示例:

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?! */ }
}

如您所见,不可能为两个接口实现该方法 - 并且也无法调用实际从给定接口实现该方法的方法。

答案 3 :(得分:4)

interface BaseInterface
{
    public function testMethod();
}

interface TestInterface extends BaseInterface
{
}

interface TestInterface2 extends BaseInterface
{
}

class TestClass implements TestInterface, TestInterface2
{
    public function testMethod()
    {
    }
}

答案 4 :(得分:-1)

这是不允许的,因为PHP无法确定哪个接口具有您想要的方法。在你的情况下,它们是相同的,但想象一下它们是否有不同的参数。

您应该重新考虑您的应用程序设计。