Search code examples
phpphp-7

Function return type hinting for an array of objects in PHP7


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.


Solution

  • I actually understand what you mean, but the answer unfortunately is that you can't do that. PHP7 lacks that kind of expressivity, so you can either declare your function to return "array" (a generic array) or you have to create a new class ItemArray which is an array of Item (but that meaning you will have to code it yourself).

    There is currently no way to express "I want an array of Item" instances.

    EDIT: As an added reference, here the "array of" RFC of what you wanted to do, it has been declined due to various reasons.