Narrow return type in PHP7

How can you narrow down the type of the return value in hints like PHP7.1?

The following code causes a fatal error Declaration of A::foo(): Obj must be compatible with IA::foo(): IObj, even when narrowing the return type, the principles of inheritance typing are not violated: Obj implements IObj, therefore, the restriction of the return type of the parent class will always be executed when the Obj instance is returned.

interface IObj {}
class Obj implements IObj {}
interface IA {
    function foo(): IObj;
}

class A implements IA {
    function foo(): Obj {
        return new Obj();
    }
}

Am I doing something wrong, or is this a flaw in PHP?

+4
source share
1 answer

, Obj implements IObj PHP. Obj - , , - , , Obj implements IObj.

, , , . , , , Obj .

+5

Source: https://habr.com/ru/post/1689072/


All Articles