Cannot implement two interfaces that have the same

2020-03-23 17:27发布

This doesn't work:

interface TestInterface
{
    public function testMethod();
}

interface TestInterface2
{
    public function testMethod();
}

class TestClass implements TestInterface, TestInterface2
{

}

Gives me the error:

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

Is that correct? Why is this not allowed? Doesn't make sense to me.

This also happens with abstract functions, for example if you implement an interface and then inherit from a class that has an abstract function of the same name.

5条回答
该账号已被封号
2楼-- · 2020-03-23 17:49

This is not allowed, because PHP cannot be sure which interface has the method you want. In your case they are identical, but imagine if they had different parameters.

You should reconsider your application design.

查看更多
干净又极端
3楼-- · 2020-03-23 17:55

It makes no sense to implement two interfaces containing methods with the same signatures.

The compiler cannot know if the methods actually have the same purpose - if not, it would mean that at least one of the interfaces cannot be implemented by your class.

Example:

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

So as you see, it's impossible to implement the method for both interfaces - and it'd also be impossible to call the method which actually implements the method from a given interface.

查看更多
冷血范
4楼-- · 2020-03-23 18:07
interface BaseInterface
{
    public function testMethod();
}

interface TestInterface extends BaseInterface
{
}

interface TestInterface2 extends BaseInterface
{
}

class TestClass implements TestInterface, TestInterface2
{
    public function testMethod()
    {
    }
}
查看更多
做个烂人
5楼-- · 2020-03-23 18:11

The PHP manual says explicitly:

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.

查看更多
forever°为你锁心
6楼-- · 2020-03-23 18:12

It appears that current PHP versions actually can do this. I've tracked the change in behavior down to this commit:

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

So as of php-5.3.9 the documented behavior appears to have changed.

查看更多
登录 后发表回答