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?
In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared. int. float. bool. string. interfaces.
Another useful feature for people who like strong typing is PHP’s return type declarations . While type hinting allows you to specify a function’s input variable types, return typing allow you to specify a function’s output variable type. Let’s look at our string to integer converter:
PHP 7 uses two types of hinting in scalar type declaration and return type declaration − By default, PHP 7 works in weak type checking mode.Weak type checking will not give any error or fatal error.When a type declaration mismatch occurs it will simply execute the code without throwing any error.
PHP 7 won't support nullable return-types just yet, but there's an RFC out to address just that, it aims to land in PHP 7.1. If it passes, the syntax would then affect all type-hints (both return types and type-hints): Show activity on this post. Nullable Types are available in PHP 7.1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With