Narrow return type in PHP7

Viewed 524

Is it somehow possible to narrow return type in PHP7.1 type hints?

The following code causes fatal error Declaration of A::foo(): Obj must be compatible with IA::foo(): IObj, even through narrowing the return type does not break inheritance typing principles: Obj implements IObj, therefore parent class return type constraint will be always satisfied when 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 PHP drawback?

1 Answers

There's no guarantee that Obj implements IObj as far as PHP is concerned. Because you may at any time move the declaration of Obj into some other file, and since files are loaded at runtime and not in some compile step, it's entirely unknown what implementation of Obj will be loaded at runtime and whether that will implements IObj.

So, no, you cannot change the return type in an implementation since then all type safety goes out the window. Type safety could only be guaranteed if you pre-compiled the code which nails down what exactly Obj will be in advance.

Related