Function return type hinting for an array of objects in PHP7
✔ Recommended Answer
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.
Source: stackoverflow.com
Answered By: Johnny
PHP 7 introduced the ability to specify the return type of a function, including an array of objects. To specify that a function returns an array of objects, you can use the following syntax:
phpfunction myFunction(): array
{
// function code here
}
In this example, the : array
syntax specifies that the function returns an array, and the absence of a specific type before the []
means that the array can contain any type of object.
If you want to specify that the array can only contain objects of a certain class, you can do so by including the class name before the []
:
phpfunction myFunction(): array
{
return [new MyClass(), new MyClass()];
}
class MyClass {}
In this example, the MyClass
specifies that the array can only contain objects of the MyClass
class.
You can also specify the type of the array keys by using the array
syntax, like so:
phpfunction myFunction(): array
{
return [
'key1' => new MyClass(),
'key2' => new MyClass(),
];
}
In this example, the keys of the array are strings, and the values are objects of the MyClass
class.
Note that if a function is expected to return an empty array, you can specify the return type as array
or array<SomeClass>
, depending on whether you want to allow the array to contain any type of object or only objects of the SomeClass
class. For example:
phpfunction emptyArray(): array
{
return [];
}
function emptyArrayWithType(): array<SomeClass>
{
return [];
}
By using function return type hinting, you can ensure that your code is more type-safe and avoid errors caused by incorrect types being returned from functions.
Comments
Post a Comment