json_decode to custom class

json_decode to custom class

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

Stefan Bogdanescu

Founder & Senior Architect

Decoding JSON into Custom Objects Beyond stdClass

When handling incoming data, json_decode() is the standard tool in PHP's arsenal, yet its default behavior often leaves developers working with generic stdClass instances. This approach forces you to manually map properties using string keys like $data->username or $data['id']. While functional, this pattern obscures type safety and makes refactoring difficult. The answer to whether you can decode JSON into a custom class is a definitive yes, but the method you choose dictates the level of type enforcement and runtime behavior you will experience.

To achieve this, you must utilize the second argument of json_decode(). By passing true as the second parameter, the function returns an associative array instead of an object. While arrays are not objects, they are closer than stdClass to a structured representation. However, if your goal is strictly object-oriented, you need to look at how PHP handles type coercion and custom constructors.

The most robust modern approach involves creating a class that explicitly declares its properties with typed hints and leveraging the magic method __construct(). When you pass an associative array (generated via json_decode($json, true)) into such a constructor, PHP attempts to map the array keys to class properties based on name matching.

Consider a simple API response handler:

class UserProfile {
    public string $username;
    public int $age;
    public ?string $bio;

    public function __construct(array $data) {
        // PHP maps array keys to typed properties automatically
        if (isset($data['username'])) {
            $this->username = $data['username'];
        }
        
        if (isset($data['age'])) {
            $this->age = $data['age'];
        }

        if (isset($data['bio'])) {
            $this->bio = $data['bio'];
        }
    }
}

$json = '{"username": "dev", "age": 28, "bio": null}';
$object = new UserProfile(json_decode($json, true));

In this scenario, the __construct() method acts as an explicit contract. You define exactly what data you expect and how it should be handled. This is superior to relying on automatic property promotion during instantiation because it gives you control over initialization logic, validation, and default values before the object enters your application flow.

However, there is a significant trade-off regarding type safety if you skip the explicit constructor mapping. If you declare typed properties but instantiate the class directly with json_decode($json, false) (which returns an object), PHP will attempt to populate the properties dynamically. This works only if the JSON keys match the property names exactly and if you do not have strict typing enforced in a way that causes errors during assignment. More importantly, if you rely on automatic mapping without a constructor, you lose the ability to set default values or handle missing keys gracefully without extensive error handling later.

A common pitfall is assuming that json_decode will validate types for you. If your JSON contains "age": "twenty", and you expect an integer property, relying on implicit casting can lead to subtle bugs where string numbers persist as strings until a specific arithmetic operation occurs. By using the array-to-object conversion method with an explicit constructor, you can insert validation logic immediately upon instantiation:

if (!is_numeric($data['age'])) {
    throw new InvalidArgumentException("Invalid age provided in JSON payload.");
}

This pattern ensures that your custom classes always hold valid state. It prevents the propagation of malformed data through your application layers. For complex structures, this manual mapping inside the constructor is often cleaner than trying to force json_decode to behave magically with a combination of flags and property promotions.

If you are working within the Laravel ecosystem, similar patterns exist for casting model attributes, but understanding the underlying mechanics of json_decode allows you to handle raw API responses outside of Eloquent models when necessary. The decision ultimately rests on whether you prefer the flexibility of dynamic object creation or the safety of explicit initialization logic.

Our network