Robert Limanto Robert Limanto - 1 year ago 144
PHP Question

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

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download