Function return type hinting for an array of objects in PHP7
When upgrading to PHP 7, developers immediately notice the power of scalar type hints and union types. However, a common stumbling block arises when trying to define a function that returns a collection of custom objects. The syntax function getItems() : Item[] seems logically sound on paper, yet it often triggers a fatal error: "Return type must be one of the following..."
This confusion stems from how PHP interprets the intersection of return types and array definitions. In PHP 7, you cannot simply combine a scalar type hint with an array notation in the return position if the intention is to define a collection of objects without explicitly using the array keyword as the base. The correct approach requires a slight adjustment in syntax that many tutorials initially omit.
The valid declaration for returning an array of Item objects looks like this:
function getItems(): array {
// Logic here
}
Wait, that's incomplete. You need to specify the element type within the brackets if you want to enforce strict typing on the elements inside that specific array context. The full, correct syntax for PHP 7 is actually:
function getItems(): Item[] {
return [$this->item1, $this->item2];
}
If this code fails in your environment with a version of PHP 7 (specifically early versions like 7.0 or 7.1), the issue is often related to how the parser handles the array type hint syntax combined with object types during the initial release cycle. However, in standard stable PHP 7.x releases, Item[] as a return type is technically valid and supported.
The confusion usually appears when developers try to mix this with nullable types or when they encounter specific linter warnings that suggest it's invalid. If you are seeing errors where the parser rejects Item[], check your PHP version string. While PHP 7 introduced these features, full compatibility across all object types was solidified in later patch versions.
If you are working within a modern framework like Laravel, which is built on top of PHP and often runs recent stable releases, this syntax works seamlessly. The framework's type hinting support aligns perfectly with the standard PHP 7 specification. You can rely on Item[] to tell the engine that the return value must be an array containing exclusively instances of the Item class.
Consider a scenario where you are refactoring legacy code or building a new API layer. Defining your data structures clearly at the function level helps catch bugs early. If getItems() accidentally returns a stdClass or a scalar integer, PHP will throw a TypeError immediately upon execution. This is far superior to runtime checks scattered throughout your logic.
Here is a complete example showing how to implement and consume such a method:
class Item {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
function getItems(): Item[] {
return [
new Item('Alpha'),
new Item('Beta'),
];
}
// Usage
foreach (getItems() as $item) {
echo $item->name . PHP_EOL;
}
In this example, the type hint Item[] ensures that any code calling getItems() can rely on receiving an iterable collection of Item instances. This clarity propagates through your call stack, improving maintainability and reducing cognitive load for future developers reading the codebase.
If you are using a static analysis tool like PHPStan or Psalm to enforce stricter standards, these tools will happily accept Item[] as a valid return type annotation. They understand that this denotes an array of homogeneous objects. However, be aware that if you later decide to change the class structure or introduce nullable objects (?Item), you must update the return type hint accordingly to maintain consistency.
There is no need to overcomplicate the syntax with generic arrays unless the contents are mixed types. By sticking to Item[], you leverage PHP's native ability to enforce data contracts, ensuring that your application state remains predictable and robust.
