Anonymous Functions and Closures

6.Anonymous Functions and Closures

M

In this chapter

We'll learn how to write a function without a name, store it in a variable and pass it around, how use lets such a closure capture variables from around it — by value at the moment it's created, which is why changing the rate later didn't change the rule — and how to capture by reference when you really need to.

13–15 min

The Problem in Real Life

Olivia wants holiday rates that can differ per day. Mia stores each day's rule as a small function in an array: $rules["2026-12-28"] = function (int $pence) use ($rate) { ... };. She sets $rate = 10;, builds the bank-holiday rule, then sets $rate = 20; and builds the Christmas Eve rule.

Then Olivia decides the bank holiday should be 15%, so Mia changes $rate = 15; at the top and runs the prices again. The bank-holiday rule still charges 10%.

M

I changed the rate. Why does the rule still use the old one?

Mia

A Named Function vs. a Function as a Value

Functions as values

A rule for each day is a function you can store in an array, pass to another function, or choose at runtime.

Closed rooms again

Like any function, an anonymous function can't see the variables around it — unless you list them with use.

Captured when created

use copies the variable's value at the moment the function is created. Later changes don't reach it.

Anonymous Functions and Closures

Functions without names: so far every function had a name and lived at the top level of a file. PHP also lets you create a function as a value, right where you need it:

  • Anonymous functions: function (int $pence) { ... } with no name, stored in a variable or passed directly.
  • Closures and use: bringing variables from around the function into it.
  • Capture by value or by reference: what use ($rate) and use (&$rate) each remember.

Anonymous functions: write function, the parameters and the body, but no name, and you get a value you can store: $withTowel = function (int $pence): int { return $pence + 250; }; — note the semicolon at the end, because this is an assignment. Call it through the variable: $withTowel(2500). You can put such functions in an array, pass them to another function — array_map() and usort() in Act 08 took exactly these — or return them from a function (chapter 8). In PHP, the value is an object of the class Closure.

An anonymous function stored in a variable
<?php
declare(strict_types=1);
$withTowel = function (int $pence): int {
return $pence + 250;
}; // a semicolon: this is an assignment
echo $withTowel(2500), "\n"; // 2750
var_dump($withTowel instanceof Closure); // bool(true)
$addOns = [
"towel" => function (int $pence): int { return $pence + 250; },
"trim" => function (int $pence): int { return $pence + 1000; },
];
echo $addOns["trim"](2500), "\n"; // 3500

use: bringing variables in: an anonymous function is a closed room, like any function (chapter 5): it can't see $rate from the code around it. To let it in, list it after the parameters: function (int $pence) use ($rate): int { ... }. A function that carries variables from where it was created is called a closure. You can list several variables, use ($rate, $minimum), and use them inside like parameters.

Without use, the closure can't see $rate
<?php
$rate = 10;
$noUse = function (int $pence): int {
return $pence + intdiv($pence * $rate, 100); // $rate is undefined in here
};
$withUse = function (int $pence) use ($rate): int {
return $pence + intdiv($pence * $rate, 100);
};
echo $noUse(2750), "\n";
echo $withUse(2750), "\n";
// Warning: Undefined variable $rate
// 2750
// 3025

Captured by value, at creation: use ($rate) copies the value of $rate into the closure at the moment the closure is created, and the closure keeps that copy for ever. That's Mia's bug: the bank-holiday rule was created while $rate was 10, so it holds 10. Changing $rate afterwards changes the outer variable, not the closure's copy. This is usually exactly what you want — each rule keeps the rate it was built with, and the Christmas Eve rule keeps its 20 — so the real fix is to create the rule after setting the rate you want, or to pass the rate in as a parameter.

Mia's bug: use copies the value at creation
<?php
$rules = [];
$rate = 10;
$rules["bank holiday"] = function (int $pence) use ($rate): int {
return $pence + intdiv($pence * $rate, 100);
};
$rate = 20;
$rules["Christmas Eve"] = function (int $pence) use ($rate): int {
return $pence + intdiv($pence * $rate, 100);
};
$rate = 15; // too late: both rules already hold their copy
foreach ($rules as $day => $rule) {
echo "$day: ", $rule(2750), "\n";
}
// bank holiday: 3025
// Christmas Eve: 3300

Capture by reference: use (&$rate) captures the variable itself instead of a copy, so the closure sees later changes and can even change the outer variable. It's occasionally useful — a counter that a callback increases — but it brings back the problems of shared state from chapters 4 and 5: the closure's result depends on whatever happens to $rate later. Use it only when you want that link on purpose. The table below compares the two.

Table — use by value vs. use by reference
Questionuse ($rate)use (&$rate)
What's captured?A copy of the valueThe variable itself
When?When the closure is createdLinked for ever
Change $rate after creating the closureThe closure keeps the old valueThe closure sees the new value
Can the closure change $rate outside?NoYes
Use it forAlmost everythingCounters and other deliberate shared state
use (&$x): a deliberate link
<?php
$calls = 0;
$countedRule = function (int $pence) use (&$calls): int {
$calls++; // changes the outer $calls
return $pence + intdiv($pence * 10, 100);
};
$countedRule(2500);
$countedRule(2750);
echo "Rule used $calls times\n"; // Rule used 2 times

Closures as parameters: a parameter that should receive a function can be typed callable or Closure: function applyRule(int $pence, callable $rule): int { return $rule($pence); }. This is the start of higher-order functions — functions that take or return functions — which chapter 8 builds on. Inside classes, closures also capture $this; Act 11 comes back to that.

A parameter that takes a function
<?php
declare(strict_types=1);
function applyRule(int $pence, callable $rule): int
{
return $rule($pence);
}
$rate = 15;
$bankHoliday = function (int $pence) use ($rate): int {
return $pence + intdiv($pence * $rate, 100);
};
echo applyRule(2750, $bankHoliday), "\n"; // 3162
echo applyRule(2750, function (int $p): int { // or written right in the call
return $p - 500;
}), "\n"; // 2250

Key Takeaway

An anonymous function is a function without a name, used as a value: stored in a variable, kept in an array, passed to or returned from another function. Like any function, it can't see outer variables — use ($x) brings them in, as a copy taken when the closure is created, so later changes don't reach it. use (&$x) shares the variable instead; use that only on purpose.

Why This Matters

Storing behaviour in a variable is what lets BookBay keep one rule per day, one price adjustment per add-on, one comparison per sort order — chosen at runtime instead of hard-wired in an if chain. Every callback in Act 08 was a closure.

And knowing exactly what a closure remembers — a copy, taken when it's created — prevents a whole class of "I changed it, why didn't it change?" bugs, in PHP and in JavaScript alike.

The rules are now built after the rates are set, and the bank holiday charges 15%. Mia rewrites the rules in the short form from Act 08, fn($p) => ..., and adds a counter of how many prices were calculated with it, fn($p) => $count++ .... The prices are right — and the counter stays at 0. That's the next chapter: arrow functions and first-class callables.