Looping through all the properties of object php

Looping through all the properties of object php

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

Stefan Bogdanescu

Founder & Senior Architect

Why foreach on Objects Fails and What to Use Instead

You are looking for a way to iterate over an object's properties without manually echoing $obj->name or $obj->age. It is a natural desire to treat an object like an associative array, hoping that a simple foreach ($obj as $property => $value) will do the trick. Unfortunately, this syntax does not work in standard PHP.

The language engine treats objects and arrays fundamentally differently under the hood. When you use foreach on an array, it iterates over the keys and values stored in the internal hash table. However, when you pass an object to foreach, the loop expects the object to implement the Traversable interface or to be iterable via a specific magic method. Standard objects do not possess these traits by default. Consequently, attempting to run foreach ($obj as ...) will result in a fatal error or simply yield no results, depending on the PHP version and specific object state.

To achieve dynamic property iteration, you must leverage PHP's magic methods: __get() and __set(). However, there is a critical distinction between accessing properties via these methods and iterating over them. The foreach loop specifically looks for an implementation of the Iterator interface or relies on the getProperties() function to extract data if the object is not iterable.

The most robust and standard approach to iterate over all public properties of an object without using foreach directly on the instance itself is to use the built-in get_properties behavior available in PHP 7.4+ via the ReflectionClass class, or by implementing the ArrayAccess and IteratorAggregate interfaces if you control the object's definition.

If you simply need to dump properties for debugging or logging, the get_object_vars() function is your best friend. This function returns an associative array containing all public properties of the given object, their values, and their names. You can then loop through that resulting array:

$properties = get_object_vars($obj);

foreach ($properties as $key => $value) {
    echo "Property: {$key}, Value: {$value}\n";
}

This method is safe because it explicitly converts the object's state into a native array structure before iteration begins. It handles the internal complexity of property access, allowing you to write clean, readable loops that mimic array syntax.

However, get_object_vars() has limitations. By default, it only returns public properties. If your object contains protected or private properties, they will be excluded from the returned array unless you use ReflectionClass to inspect them manually. This is a significant trade-off if you are working with complex domain objects that rely on encapsulation.

If you require access to private members, you must step into reflection:

$reflection = new ReflectionClass($obj);

foreach ($reflection->getProperties() as $property) {
    // Set visibility to public temporarily for reading
    $property->setAccessible(true);
    
    $name = $property->getName();
    $value = $property->getValue($obj);
    
    echo "Property: {$name}, Value: " . var_export($value, true) . "\n";
}

While verbose, this approach is the only way to reliably inspect private data without modifying the original class. It is essential to remember that setAccessible(true) bypasses visibility checks, which can introduce security risks if used in untrusted contexts or production environments where encapsulation must be strictly enforced.

In modern PHP development, especially within frameworks like Laravel, you often encounter objects that need to behave like arrays (e.g., Eloquent models). In those cases, the framework implements ArrayAccess and related interfaces to allow direct syntax like $user['name']. But for raw object iteration, relying on get_object_vars() for public data and ReflectionClass for private data provides a complete, accurate, and version-agnostic solution.

If you are building reusable utility libraries where this pattern appears frequently, consider encapsulating the logic into a helper function. This keeps your main business logic clean while abstracting away the necessary reflection or array conversion steps. Always verify whether the object exposes its data publicly first; if it doesn't, reflection is mandatory.

Our network