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.
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);
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.
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.
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.
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.
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.