Using json_encode on objects in PHP (regardless of scope)

Using json_encode on objects in PHP (regardless of scope)

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

Stefan Bogdanescu

Founder & Senior Architect

Using json_encode on objects in PHP (regardless of scope)

When you try to serialize a custom object with json_encode, expecting it to magically inspect private properties and output valid JSON, you will almost always get an empty object {}. This happens because the default behavior of json_encode is strict: it only serializes public properties that are not magic methods. The var_dump in the source material shows a RedBean_OODBBean instance where all relevant data lives inside a private property (properties). Even if you iterate through the object or make it iterable, json_encode skips over these internal structures unless they are explicitly exposed as public members.

If your goal is to output lists of objects as JSON without manually iterating and converting each item individually, relying on custom recursive functions like the one provided in the source code is a valid workaround, but it comes with significant caveats. The function json_encode_objs attempts to bypass json_encode by manually constructing a string representation. While this works for simple cases, it replicates functionality that has already been solved within the standard library, often introducing security risks and performance overhead.

Understanding Property Visibility

The core issue is property visibility. In PHP, json_encode does not traverse private properties (["properties":"RedBean_OODBBean":private]) or protected properties by default. To get data out of a RedBean object or any similar ORM-like wrapper without writing custom serialization logic, you must expose the data to the serializer.

There are two primary ways to handle this:

  1. Make Properties Public: You can use the RedBean\PHP\RedModel API (specifically the rb facade) to convert beans into plain associative arrays using methods like r::cast() or by accessing the internal data structure if your framework allows it.
  2. Implement JSON Serialization Interfaces: If you control the class definition, implementing specific interfaces is the cleanest approach. PHP provides two interfaces for this purpose: JsonSerializable and ArrayAccess.

Implementing JsonSerializable

The most robust solution is to implement the JsonSerializable interface. This interface requires a single method, jsonSerialize(), which tells json_encode exactly what data structure to use instead of the object itself.

When you call json_encode() on an object that implements this interface, PHP will internally call your jsonSerialize() method and encode the returned value (usually an array or another object) instead of trying to inspect the original class's public properties.

Here is how you can refactor a custom User object to support direct serialization:

class User implements JsonSerializable {
    private $properties; // Your existing data structure

    public function __construct(array $data) {
        $this->properties = $data;
    }

    public function getRelatedUsers(): array {
        // Logic to fetch related users
        return [];
    }

    public function jsonSerialize(): array {
        // Return only the data you want in the JSON output
        return [
            'id' => $this->properties['id'],
            'userName' => $this->properties['UniversalUserName'],
            'userType' => $this->properties['userType'],
        ];
    }
}

// Usage
$related = $user->getRelatedUsers();
$json = json_encode($related); // Now works correctly without manual iteration

Why Custom Recursive Functions Are Risky

The source material suggests using a custom recursive function to manually build the JSON string. While this approach forces the object's contents into a string, it generally violates best practices for several reasons:

  • Security: Manually constructing strings involving user data without proper escaping can lead to vulnerabilities if not handled with extreme care. json_encode handles escaping automatically and safely; replicating this logic manually is error-prone.
  • Magic Methods: The custom function in the source code relies on iterating over keys. If the object has magic methods like __get() or __set(), a manual iteration might not capture dynamic properties correctly, leading to missing data. json_encode respects these magic methods when serializing objects.
  • Maintainability: A custom serializer couples your output format tightly to your internal class structure. If you add a new property to the object later, your custom function must be updated to handle it, whereas JsonSerializable allows you to simply return an array with the new key.

Trade-offs and Recommendations

If you are using a library like RedBean where you cannot easily modify the core bean class, you should check if the library provides a cast method (e.g., r::cast($bean)). This converts the object into a plain array before serialization, which json_encode handles natively.

If you must serialize objects that are not under your direct control, wrapping them in an anonymous class or a simple DTO (Data Transfer Object) that implements JsonSerializable is often cleaner than writing global recursive functions.

Using the native json_encode with proper interfaces ensures consistency, security, and compatibility with PHP's built-in error handling. Custom serialization logic should only be used when dealing with legacy codebases where refactoring is impossible, and even then, it requires a deep understanding of how JSON_HEX_TAG, JSON_HEX_APOS, and JSON_HEX_QUOT flags affect the output.

Our network