Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function return type hinting for an array of objects in PHP7

Tags:

php

php-7

I am very happy with the new features in PHP 7. But I am confused on how to return an array of objects in PHP 7.

For example, we have a class Item, and we want to return an array of objects of this class from our function:

function getItems() : Item[] { } 

But it does not work this way.

like image 311
Robert Limanto Avatar asked Nov 19 '16 13:11

Robert Limanto


People also ask

What is type hinting in PHP with example?

Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.

Which data types can be declared with type hinting in PHP?

In simple word, type hinting means providing hints to function to only accept the given data type. In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type. In PHP, we can use type hinting for Object, Array and callable data type.


1 Answers

You can type hint this way using docblocks.

PHP editor (IDE) like PhpStorm supports this very well and will properly resolve the class when iterating over such array.

/**  * @return YourClass[]  */ public function getObjects(): iterable 

PHPStorm also supports nested arrays:

/**  * @return YourClass[][]  */ public function getObjects(): iterable 

Newer versions of PHPStorm support phpstan/psalm format:

/**  * @return array<int, YourObject>  */ public function getObjects(): array 
like image 56
emix Avatar answered Sep 21 '22 13:09

emix