Search code examples
phpinterfacecompatibilitytype-hinting

Why does PHP emit compatibility error when inherited interfaces are used for type hinting?


Please take a closer look at the following two code blocks. Error and Warning produced are placed underneath the respective code block.

It seems very interesting to me! I think both should act in the same way, and those should not emit any error or warning as they seems logically valid to me.

Is this a PHP bug, or I'm missing something?

By the way, I believe the question and the code is very simple and self-explanatory, so I'm not going for further explanation. :-)

interface A {}

interface B extends A {}

class X implements A {
    public function test() : A {}
}

class Y extends X implements B {
    public function test() : B {}
}

Fatal error: Declaration of Y::test(): B must be compatible with X::test(): A

interface A {}

interface B extends A {}

class X implements A {
    public function test( A $a ) {}
}

class Y extends X implements B {
    public function test( B $b ) {}
}

Warning: Declaration of Y::test(B $b) should be compatible with X::test(A $a


Solution

  • I think I found the answer myself.

    As an inherited interface can have additional declarations (an inherited type can have additional attributes), those are logically completely different, and hereby the Error / Warning emitted by PHP are absolutely correct.

    Thank you for reading the question and the answer. Hopefully this will help others understand the use of interfaces as type in a better way.