Type hinting in PHP 7 - array of objects

Type hinting in PHP 7 - array of objects

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Type Hinting in PHP 7: Arrays of Objects

There was no native way to type hint an array of objects directly in PHP 7. While you could specify that a function expects an array (array $users) or returns an array (: array), the language did not support specifying the element type within that array using standard syntax like array<User> or just User[].

The code snippet provided illustrates a common frustration during that era of PHP development. You have a clean User class with strict property types and return types, yet the function findUserByAge returns an inconsistent result depending on the logic inside the loop:

function findUserByAge(int $age, array $users) : array {
    $result = [];
    foreach ($users as $user) {
        if ($user->getAge() == $age) {
            if ($user->getName() == 'John') {
                // complicated code here
                $result[] = $user->getName(); // Returns string
            } else {
                $result[] = $user;         // Returns User object
            }
        }
    }

    return $result;
}

In this specific example, $result is technically an array of mixed. Even though the function signature declares it returns an array, PHP has no compile-time (or even strict runtime without extra flags) way to enforce that every element inside that array is a User object. If you try to access $user->getName() on the returned array immediately after calling the function, you risk a fatal error if one of the elements was a string.

How PHP 7 Handled This

When PHP 7 introduced type hints, it focused on scalar types (int, string, bool, float), callable, and generic containers like array. It did not introduce covariance or contravariance for generic collections in the same way modern generics do in statically typed languages like Java or C#.

The reason was largely pragmatic. Implementing full generic type checking for arrays required a significant shift in how the Zend Engine handled memory and type validation. At the time, PHP prioritized backward compatibility and performance overhead. Adding strict array element type checking would have forced the engine to validate every single element upon creation, iteration, or access, which could introduce unacceptable latency for high-performance web applications.

The Solution: Union Types in PHP 8.0+

If you are maintaining legacy code written in PHP 7, you must accept that mixed is the implicit return type for arrays of mixed elements. You can mitigate risks by enforcing strict typing rules at runtime or refactoring to ensure consistency, but the language itself offers no declaration for this specific case.

However, if your project allows an upgrade, PHP 8.0 changed this landscape entirely with Union Types and Generics support (specifically via array type hints becoming more robust in later versions). But strictly speaking, within the constraints of PHP 7, the only way to define a function that returns an array of User objects is through documentation or external static analysis tools like Psalm or PHPStan.

These tools can analyze your codebase and warn you if $result contains strings when it should contain User objects, effectively acting as the missing type hint system for complex data structures. You would configure a tool to check:

/**
 * @return User[]
 */
function findUserByAge(int $age, array $users): array {
    // ... logic ...
}

While this doesn't stop PHP from executing the code, it prevents developers from making mistakes at the call site by providing accurate IDE autocomplete and refactoring support.

Why Not in PHP 7?

The omission of User[] syntax in PHP 7 was a deliberate design choice favoring flexibility over strictness. The PHP community viewed the array as a loose container that could hold anything. Introducing rigid constraints would have broken existing patterns where arrays were used for heterogeneous data collections, a common practice even in modern web stacks.

For developers stuck on PHP 7, the trade-off is clear: gain type safety for scalar values and simple objects via return types, but rely on static analysis tools or internal consistency checks to manage complex array structures. This distinction remains relevant until you move to environments where full generic typing is supported.

Our network