Serializing PHP object to JSON

Serializing PHP object to JSON

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

Stefan Bogdanescu

Founder & Senior Architect

Serializing PHP Objects to JSON

When working with legacy systems or maintaining older codebases, you often encounter environments running PHP versions prior to 5.4. In these scenarios, the JsonSerializable interface is unavailable, leaving developers with a specific problem: how to convert complex object graphs into JSON without breaking the serialization process.

By default, json_encode() treats objects as opaque entities. If an object does not implement JsonSerializable, PHP attempts to serialize only the properties that are currently accessible via public getters or direct property access in a very limited way. Frequently, this results in an empty JSON object ({}), even if the object's internal state appears robust when inspected via var_dump().

Consider a scenario where you have a custom data structure, perhaps a tree node class named Mf_Data, containing nested objects and private properties. When you pass an instance of this class directly to json_encode(), the output is often just {}. This happens because json_encode() does not automatically traverse into complex object hierarchies or handle private/protected internal structures without explicit direction.

To solve this in PHP < 5.4, the standard pattern is to manually transform the object into an associative array before encoding it. The core of this solution lies in writing a recursive toArray() method that walks through the object's properties and ensures every nested object is also converted into an array.

Here is a practical implementation for a class like Mf_Data. The goal is to flatten the object structure so that json_encode() receives a standard PHP array:

public function toArray()
{
    // Get all public and protected properties, excluding internal references
    $array = get_object_vars($this);
    
    // Filter out internal bookkeeping properties like _parent or _index
    unset($array['_parent'], $array['_index']);
    
    // Recursively convert nested objects to arrays
    array_walk_recursive($array, function (&$property) {
        if (is_object($property) && method_exists($property, 'toArray')) {
            $property = $property->toArray();
        }
    });
    
    return $array;
}

This approach relies on get_object_vars() to retrieve the current state of the object. The subsequent unset() calls are critical; if you leave internal references to parent nodes or index counters in the array, json_encode() might output them, potentially leading to circular reference issues or leaking internal implementation details.

A common pitfall when implementing this pattern is handling circular references. If your data structure forms a tree where nodes reference their parents (as seen with _parent), a naive recursive function will trigger a stack overflow. The source material highlights that removing these parent references resolves the recursion issue. While interfaces like ToMapInterface offer a cleaner abstraction for type checking—replacing magic method_exists() checks—they introduce their own overhead by copying property arrays via array_diff_key.

The trade-off between using method_exists() and defining an interface depends on your architecture. If you are dealing with a deeply nested tree structure where circular references are possible, explicit exclusion of parent pointers in the conversion logic is mandatory. Once the object is successfully converted to a flat array via this manual transformation, passing it to json_encode() yields a valid, serializable string ready for API consumption.

For modern applications, checking if PHP version 5.4 or higher is available allows you to simply implement JsonSerializable. However, for those constrained to older versions, the manual array conversion strategy remains the most reliable way to ensure data integrity during serialization.

Our network