Anonymous classes

← Anonymous classes

Ashterix

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

1 + # Anonymous classes
2 +
3 + *An old feature that plenty of developers still ignore*
4 +
5 + - **Added in:** PHP 7.0
6 + - **What it gives you:** the ability to create a class "on the fly" β€” no name, no separate file, right where you actually need it.
7 +
8 + ## Why it's worth bringing up
9 +
10 + Even though anonymous classes appeared back in PHP 7, talking to developers gives me roughly these numbers:
11 +
12 + - 9 out of 10 see no "practical point" in them;
13 + - 7 out of 10 have never tried to write `new class {}`, not even in pet projects or drafts.
14 +
15 + And that's a shame β€” it's a tool that is perfect for temporary objects, adapters, wrappers and strategies.
16 +
17 + ## When anonymous classes really come in handy
18 +
19 + - when you need a mock object for tests;
20 + - when you need to override an object's behaviour just here and now;
21 + - when you don't want to create a separate class for a tiny bit of logic;
22 + - when you need to adapt or extend behaviour "locally";
23 + - when you need a small object with its own state or a few methods.
24 +
25 + ## Real-world examples
26 +
27 + 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.
28 +
29 + ### A temporary adapter
30 +
31 + ```php
32 + $adapter = new class($apiClient) implements PaymentGateway
33 + {
34 + public function __construct(private ApiClient $api) {}
35 +
36 + public function pay(float $amount): bool {
37 + return $this->api->request('/pay', ['sum' => $amount]);
38 + }
39 + };
40 +
41 + $adapter->pay(9.99);
42 + ```
43 +
44 + A couple of lines β€” and you have a ready-made adapter without creating a file.
45 +
46 + ### A local strategy or callback object
47 +
48 + ```php
49 + $transformer = new class
50 + {
51 + public array $alreadyTransform = [];
52 + public function transform(int $v): int
53 + {
54 + return $this->alreadyTransform[$v] ??= $v*10;
55 + }
56 + };
57 +
58 + $result = array_map(
59 + $transformer->transform(...),
60 + [1, 2, 3, 2, 1, 2, 3]
61 + );
62 + var_dump($result); //[10, 20, 30, 20, 10, 20, 30]
63 + ```
64 +
65 + A callable with a method and its own state. We get a result for seven elements, but the computation runs only three times.
66 +
67 + ### A temporary event listener
68 +
69 + ```php
70 + $dispatcher->addListener('user.registered', new class {
71 + public function __invoke(User $user): void {
72 + // logging, notifications, email β€” whatever you like
73 + }
74 + });
75 + ```
76 +
77 + A one-off listener β€” and no need to bloat the number of files in the project.
78 +
79 + ### A DTO "on the fly"
80 +
81 + ```php
82 + return new class($user, $stats) {
83 + public function __construct(
84 + public User $user,
85 + public array $stats
86 + ) {}
87 +
88 + public function total(): int {
89 + return array_sum($this->stats);
90 + }
91 + };
92 + ```
93 +
94 + For when creating a separate structure for a one-off result would be overkill.
95 +
96 + ## Conclusion
97 +
98 + > Anonymous classes are an old but heavily underrated tool.
99 + > They save time, reduce the number of files and let you keep temporary logic exactly where it's needed.
100 +
101 + If you haven't tried `new class {}` yet either, do it today. You might discover a new favourite PHP trick.
102 +
103 + ← [Previous: Property Promotion](/articles/from-tg/series/php-can-do/property-promotion) Β· [Whole series](/articles/from-tg/series/php-can-do) Β· [Next: Arrow functions β†’](/articles/from-tg/series/php-can-do/arrow-functions)
104 +
105 + ---
106 +
107 + *First published in Ukrainian in the Telegram channel [β€œCreated to die”](https://t.me/php_while_true/73) on October 16, 2025.*