In this chapter
We'll learn the short arrow-function form fn($x) => ... and how it captures outer variables automatically — but only by value, which is why a counter inside it stayed at 0 — plus first-class callable syntax like strtoupper(...), the callable type, and the other ways PHP lets you refer to a function.
The Problem in Real Life
Mia rewrites the holiday rules in the short form she saw in Act 08: $rule = fn(int $p): int => $p + intdiv($p * $rate, 100);. No use needed — the arrow function sees $rate on its own. The prices are right.
Olivia wants to know how many prices the day view calculates, so Mia adds a counter to the formatting step: array_map(fn($b) => $count++ ... , $day). Twelve bookings later, $count is still 0.
The arrow function can read $rate without use. Why can't it change $count?
Mia
function () use () vs. fn() =>
Short and automatic
fn($p) => $p + 250 is one line, and it sees outer variables without use.
Read, but never write
An arrow function gets copies of the outer variables. Changing one inside changes only the copy.
Naming a function as a value
"trim" as a string, strtoupper(...), a closure: PHP has several ways to hand over an existing function.
Arrow Functions and First-Class Callables
Shorter ways to write and pass functions: most callbacks are one short expression, and many are just an existing function. PHP has compact forms for both:
- Arrow functions:
fn(int $p): int => $p + 250— one expression, automatic capture. - First-class callables:
strtoupper(...)turns an existing function into a value. - The callable type: everything PHP accepts where a function is expected.
Arrow functions: fn(int $p): int => $p + 250 is an anonymous function with one big simplification: the body is a single expression, and its value is returned automatically — no braces, no return. Types work as usual. An arrow function can't contain several statements (no foreach, no if block), so for anything longer, use function () { }. Arrow functions arrived in PHP 7.4, and they're the usual choice for short callbacks: array_map(fn($b) => $b["pence"], $day).
<?phpdeclare(strict_types=1);$withTowel = fn(int $p): int => $p + 250;echo $withTowel(2500), "\n"; // 2750$day = [["customer" => "Tom Hart", "pence" => 2500], ["customer" => "Ann Lee", "pence" => 2750]];echo implode(", ", array_map(fn($b) => $b["customer"], $day)), "\n"; // Tom Hart, Ann Leeecho array_sum(array_map(fn($b) => $b["pence"], $day)), "\n"; // 5250
Automatic capture, by value: an arrow function sees the variables of the code around it without use — PHP captures every outer variable it mentions, automatically. But it captures them the same way use ($x) does: as copies, taken when the arrow function is created. Reading works perfectly; writing doesn't: $count++ inside the arrow function increases the copy, and the outer $count stays 0. That was Mia's counter. There's no & form for arrow functions. If you need to change an outer variable, use a full closure with use (&$count), or better, don't count inside a mapping at all: count($day) gives the answer directly.
<?phpdeclare(strict_types=1);$rate = 15;$closure = function (int $p) use ($rate): int { return $p + intdiv($p * $rate, 100); };$arrow = fn(int $p): int => $p + intdiv($p * $rate, 100); // no use neededecho $closure(2750), " ", $arrow(2750), "\n"; // 3162 3162
<?php$day = [["pence" => 2500], ["pence" => 2750], ["pence" => 1000]];$count = 0;array_map(fn($b) => $count++, $day); // each call increases its own copyecho "Counted: $count\n"; // Counted: 0$count = 0;$prices = array_map(function ($b) use (&$count) {$count++; // a full closure with &: changes the outer $countreturn $b["pence"];}, $day);echo "Counted: $count\n"; // Counted: 3echo "Or simply: ", count($day), "\n"; // Or simply: 3
First-class callables: writing a function's name followed by (...) — three dots, literally — gives you the function itself as a Closure, without calling it: $upper = strtoupper(...); and then $upper("ben") is "BEN". It works for your own functions too: array_map(formatPrice(...), $prices). This is called first-class callable syntax, new in PHP 8.1, and it's the safest way to pass an existing function: a typo in the name is an error right there, on that line.
<?phpdeclare(strict_types=1);function formatPrice(int $pence): string{return "£" . number_format($pence / 100, 2);}$upper = strtoupper(...);echo $upper("ben"), "\n"; // BENecho implode(" ", array_map(formatPrice(...), [2500, 3025])), "\n"; // £25.00 £30.25try {$f = formatPrise(...); // a typo: caught right here} catch (Error $e) {echo $e->getMessage(), "\n"; // Call to undefined function formatPrise()}
The callable type and the older forms: a parameter typed callable accepts anything PHP can call: a Closure (anonymous, arrow, or made with (...)), a function name as a string like "trim", an array of an object and a method name (Act 11), or an object with an __invoke() method. The string form is common in older code — array_map("trim", $names) — but a typo there is only noticed when the function is finally called. is_callable($x) tells you whether something can be called. The table below compares the forms.
| Form | Example | Notes |
|---|---|---|
| Anonymous function | function (int $p) use ($rate): int { ... } | Any number of statements; explicit use |
| Arrow function | fn(int $p): int => $p + 250 | One expression; automatic capture by value |
| First-class callable | formatPrice(...) | An existing function as a Closure; typos fail at once |
| Function name as a string | "trim" | Older style; typos found only when called |
| Object and method | [$object, "method"] | Act 11 |
<?phpprint_r(array_map("trim", [" Ben ", " Leo"])); // the older string form// Array// (// [0] => Ben// [1] => Leo// )var_dump(is_callable("trim")); // bool(true)var_dump(is_callable("formatPrise")); // bool(false): no such functionvar_dump(is_callable(fn() => 1)); // bool(true)
Key Takeaway
fn($x) => expression is a one-expression anonymous function that returns its value automatically and captures outer variables without use — by value, so it can read them but never change them. For several statements or writing to outer variables, use function () use (&$x) { }. name(...) turns any function into a Closure (PHP 8.1); a callable parameter accepts closures, function-name strings and other callables.
Why This Matters
Arrow functions are what make array_map(), array_filter() and usort() pleasant to use; you'll write dozens of them a day. Knowing that they read but never write outer variables keeps you from hiding side effects in them — which is also the right habit: a mapping step should only map.
First-class callables make passing existing functions safe and readable, and they're how modern PHP and Laravel code hands functions around.
The counter is gone — count($day) does the job — and the formatting step uses formatPrice(...). Now Olivia wants the price rules to be configurable: a list of steps applied one after another — base price, add-ons, holiday surcharge, staff discount — that she can reorder without asking Mia. Mia writes array_map(formatPrice(), $prices) by mistake and gets an ArgumentCountError. That's the next chapter: callbacks and higher-order functions.
