Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Narrow return type in PHP7

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?

like image 939
amik Avatar asked Nov 10 '17 14:11

amik


People also ask

What is return type in PHP 7?

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.

What is the difference between type hinting and return typing in PHP?

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:

What are the types of hinting in PHP 7?

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.

Is there a nullable return type in PHP7?

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.


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.

like image 84
deceze Avatar answered Sep 17 '22 11:09

deceze