Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implement two interfaces that have the same method name

Tags:

oop

php

interface

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.

like image 735
Gnuffo1 Avatar asked Mar 31 '11 09:03

Gnuffo1


People also ask

CAN 2 interfaces have the same method name?

The implementation of interface's members will be given by the class who implements the interface implicitly or explicitly. C# allows the implementation of multiple interfaces with the same method name.

Can we implement two interfaces with same method?

So, if the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect. However, if two interfaces implement the same default method, then there is a conflict.

Can a class implement two interfaces with the same default method?

Classes can implement more than one interface. As interface can consist of default methods in Java 8, which a class does not necessarily need to implement. We can have two interfaces that have default methods with the same name and signature.

What happens if a class implements two interfaces which specify the exact same method?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error.


1 Answers

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.

like image 168
TheBigB Avatar answered Oct 09 '22 14:10

TheBigB