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?
source
share