Arrow functions

← Arrow functions

Ashterix

docs: English JsonRpcBundle docs, REST and MCP Bundle sections, package cards

en/articles/from-tg/series/php-can-do/arrow-functions.md new file +70 βˆ’0

1 + # Arrow functions
2 +
3 + *Like a closure, only slimmer*
4 +
5 + - **Added in:** PHP 7.4
6 + - **What it gives you:** a compact syntax for short functions that automatically see variables from the surrounding scope and always return a result.
7 +
8 + ## Things you need to know
9 +
10 + - they always return a value;
11 + - they can contain only a single expression β€” no `{}` and no multi-statement blocks;
12 + - they automatically inherit variables from the surrounding scope, without `use($x)`;
13 + - they read as an expression, not as a statement.
14 +
15 + ## Why it's convenient
16 +
17 + - less boilerplate;
18 + - expressiveness in callbacks (map, filter, reduce);
19 + - better readability, especially in collections and streams;
20 + - a fit for any place where you need a minimal handler.
21 +
22 + ## Real-world examples
23 +
24 + ### Transforming an array
25 +
26 + ```php
27 + $prices = [100, 200, 300];
28 + $tax = 0.2;
29 +
30 + // ❌ A regular anonymous function
31 + $withTax = array_map(function (int $p) use ($tax) {
32 + return $p * (1 + $tax);
33 + }, $prices);
34 +
35 + // βœ… An arrow function
36 + $withTax = array_map(fn(int $p) => $p * (1 + $tax), $prices);
37 + ```
38 +
39 + ### Filtering elements
40 +
41 + ```php
42 + $activeUsers = array_filter($users, fn(User $u) => $u->active);
43 + ```
44 +
45 + ### Computing a value
46 +
47 + ```php
48 + $total = array_reduce($orders, fn(int $sum, Order $o) => $sum + $o->amount, 0);
49 + ```
50 +
51 + ### A simple calculator with access to an outer variable
52 +
53 + ```php
54 + $multiplier = 3;
55 + $calc = fn(int $v) => $v * $multiplier;
56 +
57 + echo $calc(10); // 30
58 + ```
59 +
60 + ## Conclusion
61 +
62 + > Arrow functions are a concise form of closures, made for clean, short expressions in straightforward logic.
63 +
64 + If your code has `function ($x) use ($y) { return …; }` β€” just replace it with `fn()` and feel the difference.
65 +
66 + ← [Previous: Anonymous classes](/articles/from-tg/series/php-can-do/anonymous-classes) Β· [Whole series](/articles/from-tg/series/php-can-do) Β· [Next: Generators β†’](/articles/from-tg/series/php-can-do/generators)
67 +
68 + ---
69 +
70 + *First published in Ukrainian in the Telegram channel [β€œCreated to die”](https://t.me/php_while_true/76) on October 17, 2025.*