Current Location: Home> Latest Articles> JsonSerializable with PHP Anonymous Classes: How to Elegantly Simplify Data Output?

JsonSerializable with PHP Anonymous Classes: How to Elegantly Simplify Data Output?

gitbox 2025-06-11

Scenario

Consider the following situation: you have a user model $user containing many fields such as ID, name, email, password hash, registration time, and more. When exposing an API, you might only want to return a subset of fields like ID and name, while also processing some fields, for example, concatenating URLs or formatting data. To avoid polluting the core model logic while keeping the code clean and clear, anonymous classes come in handy.


Anonymous Classes + JsonSerializable: Making Output More Elegant

Here is an example demonstrating the use of an anonymous class with JsonSerializable:

<?php

$user = (object)[
'id' => 101,
'name' => 'Alice',
'avatar' => 'avatar101.jpg',
];

function presentUser(object $user): JsonSerializable {
return new class($user) implements JsonSerializable {
private object $user;

    public function __construct(object $user) {
        $this->user = $user;
    }
    return [
        'id' => $this->user->id,
        'name' => $this->user->name,
        'avatar_url' => 'https://gitbox.net/uploads/avatars/' . $this->user->avatar,
    ];
}

};

}

header('Content-Type: application/json');
echo json_encode(presentUser($user), JSON_PRETTY_PRINT);


Code Highlights

  1. Tight Context Binding with Anonymous Classes
    The anonymous class captures the $user object via its constructor and exists only for this specific use, reducing redundant class definitions.

  2. JsonSerializable Interface Ensures Structured Output
    This interface allows you to customize serialization logic to convert an object into an array output more elegantly than traditional methods like getArrayCopy() or manual array construction.

  3. Encapsulation of Formatting Logic
    For example, the concatenation logic for the avatar_url field is neatly wrapped inside the anonymous class, avoiding handling such details in controllers or view layers.


Comparison with Traditional Approach

The traditional approach might look like this:

echo json_encode([ 'id' => $user->id, 'name' => $user->name, 'avatar_url' => 'https://gitbox.net/uploads/avatars/' . $user->avatar, ]);

Although the number of code lines is similar, when output fields grow or logic becomes more complex, the anonymous class approach provides better structure and reusability potential. Especially, this anonymous class can be further abstracted and encapsulated in a function to form a reusable Presenter layer.


Usage Recommendations

  • For temporary data encapsulation and limited-scope output, anonymous classes combined with JsonSerializable make an ideal pair.

  • If the project involves extensive DTO requirements, consider dedicated classes or automation tools (such as Symfony Serializer or Laravel Resource).

  • Avoid overusing anonymous classes: while flexible, they are not suitable for handling complex behaviors or logic that needs reuse.