docs: English JsonRpcBundle docs, REST and MCP Bundle sections, package cards
en/articles/from-tg/series/php-can-do/anonymous-classes.md
new file +107
−0
Anonymous classes
An old feature that plenty of developers still ignore
- Added in: PHP 7.0
- What it gives you: the ability to create a class "on the fly" — no name, no separate file, right where you actually need it.
Why it's worth bringing up
Even though anonymous classes appeared back in PHP 7, talking to developers gives me roughly these numbers:
- 9 out of 10 see no "practical point" in them;
- 7 out of 10 have never tried to write
new class {}, not even in pet projects or drafts.
And that's a shame — it's a tool that is perfect for temporary objects, adapters, wrappers and strategies.
When anonymous classes really come in handy
- when you need a mock object for tests;
- when you need to override an object's behaviour just here and now;
- when you don't want to create a separate class for a tiny bit of logic;
- when you need to adapt or extend behaviour "locally";
- when you need a small object with its own state or a few methods.
Real-world examples
I won't show how to create mocks for tests — the internet is full of those examples. Instead, I'll share some more practical uses of anonymous classes.
A temporary adapter
$adapter = new class($apiClient) implements PaymentGateway
{
public function __construct(private ApiClient $api) {}
public function pay(float $amount): bool {
return $this->api->request('/pay', ['sum' => $amount]);
}
};
$adapter->pay(9.99);
A couple of lines — and you have a ready-made adapter without creating a file.
A local strategy or callback object
$transformer = new class
{
public array $alreadyTransform = [];
public function transform(int $v): int
{
return $this->alreadyTransform[$v] ??= $v*10;
}
};
$result = array_map(
$transformer->transform(...),
[1, 2, 3, 2, 1, 2, 3]
);
var_dump($result); //[10, 20, 30, 20, 10, 20, 30]
A callable with a method and its own state. We get a result for seven elements, but the computation runs only three times.
A temporary event listener
$dispatcher->addListener('user.registered', new class {
public function __invoke(User $user): void {
// logging, notifications, email — whatever you like
}
});
A one-off listener — and no need to bloat the number of files in the project.
A DTO "on the fly"
return new class($user, $stats) {
public function __construct(
public User $user,
public array $stats
) {}
public function total(): int {
return array_sum($this->stats);
}
};
For when creating a separate structure for a one-off result would be overkill.
Conclusion
Anonymous classes are an old but heavily underrated tool. They save time, reduce the number of files and let you keep temporary logic exactly where it's needed.
If you haven't tried new class {} yet either, do it today. You might discover a new favourite PHP trick.
First published in Ukrainian in the Telegram channel “Created to die” on October 16, 2025.