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.
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.
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.
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
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