The Analogy: A Travelling Sales Rep Packs a Sample Case
Picture a sales rep at a warehouse on a Monday morning, packing a sample case before a week on the road. They walk the shelves and drop a few of this week's products into the case: a paint chart, three fabric swatches, a price list printed that morning. The moment the lid clicks shut and the rep drives away, the case holds exactly those items. Back at the warehouse the stock can be restocked, rearranged, marked down, or sold out entirely, and none of it touches the case. The rep is carrying independent copies of what the shelves held at packing time.
That packing step is the whole idea behind a closure. A closure is a function you can carry around like the case, and it quietly packs copies of the variables it needs from the place where it was created. Two reps who pack their cases at different moments carry different contents, even though they packed from the same shelves; likewise two closures created at different points in a program capture different values, even when the code that builds them is identical. The case remembers the warehouse as it was the instant it was packed, and a closure remembers its surrounding variables the same way.
There is a second way to equip the rep. Instead of physical samples, hand them a tablet that stays connected to the live stock system. Now whatever the warehouse currently shows is what the rep quotes to the customer, and any correction the rep types on the road is written straight back to the warehouse records. Nothing was copied; the tablet and the warehouse share one set of figures. That is capture by reference -- in PHP, writing use (&$x) instead of use ($x). The rep still carries something, but it is a live link rather than a frozen snapshot.
The trouble starts when the rep is wrong about which kind of case they are holding. If they believe the tablet is a fixed printout and quote last week's discount that the warehouse has since withdrawn, the customer is promised a price the company no longer honours. If they believe the physical case is a live link and expect it to update itself with this morning's new arrivals, they show up with stale swatches and miss the sale. Worse, if two reps unknowingly share one live tablet, each overwrites the other's notes. Every one of these failures comes from a mismatch between what was actually captured and how the rep assumes it behaves -- and that exact mismatch is the most common closure bug in PHP.
Syntax or Core Structure
A closure is created with an anonymous function. To pull variables in from the surrounding scope you list them in a use clause. By default they are captured by value: the closure packs a copy, frozen at the moment the closure is defined.
<?php
declare(strict_types=1);
$base = 10;
// Anonymous function: capture $base by value with use().
$addClosure = function (int $x) use ($base): int {
return $x + $base;
};
// Arrow function: automatically captures $base by value, no use() needed.
$addArrow = fn (int $x): int => $x + $base;
// Change $base AFTER both are defined.
$base = 999;
echo $addClosure(5), "\n"; // still uses the captured 10 -> 15
echo $addArrow(5), "\n"; // still uses the captured 10 -> 15
Both functions were built while $base held 10, so both packed the value 10 into their case. Reassigning $base to 999 afterwards changes the warehouse shelf, not the sealed cases, so each call still returns 5 + 10.
Output:
15
15
The arrow function fn () => ... is the compact form introduced in PHP 7.4. It always captures by value, always automatically, and its body is a single expression whose value is returned. The longer function () use (...) { ... } form is more verbose but can hold many statements and lets you choose value or reference capture per variable. They are two spellings of the same underlying object: an instance of the built-in Closure class.
Technical Depth: Capture Rules, References, and Binding
Three ways to define a function-shaped value
PHP now offers three closely related tools, and choosing well matters. The table below lays them side by side.
| Form | Captures outer variables | Body | Can bind $this |
|---|---|---|---|
| Named function | Never (only globals via global) | Many statements | No |
| Anonymous function | Only those you list in use() | Many statements | Yes, when defined in a method |
Arrow function fn | All it references, automatically, by value | One expression only | Yes, when defined in a method |
A named function is an island: it sees nothing of the scope around it and must be handed everything through parameters. An anonymous function is explicit -- you name exactly what it packs. An arrow function is automatic -- it captures whatever variables its single expression mentions, always by value. The automatic capture is a convenience for short callbacks, but it is also why arrow functions are deliberately limited to one expression: the shorter the body, the smaller the risk of capturing something by surprise.
By value versus by reference
The difference between use ($x) and use (&$x) is the difference between the packed case and the live tablet.
<?php
declare(strict_types=1);
// By reference: the closure shares the caller's $total.
$total = 0;
$deposit = function (int $n) use (&$total): void {
$total += $n;
};
$deposit(100);
$deposit(50);
echo $total, "\n"; // 150 -- writes flowed back
// By value: the closure froze a copy of $snapshot at definition time.
$snapshot = 0;
$peek = function () use ($snapshot): int {
return $snapshot;
};
$snapshot = 77; // changes the outer variable only
echo $peek(), "\n"; // 0 -- the frozen copy is unchanged
Output:
150
0
The $deposit closure captured $total by reference, so every call writes through the shared link and the caller sees 150. The $peek closure captured $snapshot by value, freezing 0; reassigning $snapshot to 77 afterwards touches only the outer variable, so the closure still returns its frozen 0. Reference capture is powerful for building accumulators and counters, but it turns a closure into shared mutable state -- exactly the thing that makes concurrent-looking code hard to reason about. Reach for it deliberately, not by habit.
Binding to an object with $this
A closure created inside a method captures $this automatically, so it can reach the object's properties. You can also rebind an existing closure to a different object with Closure::bind or bindTo, which is how frameworks let a template or route callback behave as if it were a method of some target object. Because this rebinding hands the closure access to another object's protected and private members, it is a sharp tool: convenient inside a framework's own plumbing, but a hole in encapsulation if scattered through ordinary application code.
Real World Example: A Discount Engine Built from Closures
A checkout needs to apply a list of discounts to an order: a percentage off for members, a flat coupon, a seasonal promotion. Each discount has its own settings, but they all share one shape -- given the current total in cents, return how much to knock off. That uniform shape is a perfect fit for closures: each rule packs its own settings and exposes the same tiny interface. The engine then walks the list and applies them in order.
<?php
declare(strict_types=1);
function money(int $cents): string {
return number_format($cents / 100, 2);
}
// Each rule packs its own settings by value and returns cents to deduct.
function percentOff(int $percent): callable {
return fn (int $total): int => intdiv($total * $percent, 100);
}
function flatOff(int $cents): callable {
return fn (int $total): int => $cents;
}
$subtotal = 20000; // $200.00 in cents
$rules = [
'Member 10%' => percentOff(10),
'Coupon SAVE5' => flatOff(500),
];
echo "RECEIPT\n";
echo str_repeat('-', 7), "\n";
printf("%-16s %10s\n", 'Subtotal', '$' . money($subtotal));
$running = $subtotal;
foreach ($rules as $label => $rule) {
$cut = $rule($running); // rule sees the running total
$running -= $cut;
printf("%-16s %10s\n", $label, '-$' . money($cut));
}
printf("%-16s %10s\n", 'Total due', '$' . money($running));
Each call to percentOff or flatOff returns a fresh closure that has packed its own $percent or $cents by value. The Member 10% rule carries 10 in its case forever; the Coupon SAVE5 rule carries 500. The engine does not know or care how each rule computes its cut -- it just hands over the running total and subtracts what comes back. This is closures used as small, self-contained strategy objects, and it reads far more directly than a chain of conditionals switching on a discount type.
Output:
RECEIPT
-------
Subtotal $200.00
Member 10% -$20.00
Coupon SAVE5 -$5.00
Total due $175.00
Tracing the arithmetic confirms the design: ten percent of 20000 cents is 2000, leaving 18000; the flat coupon removes another 500, leaving 17500, printed as $175.00. The percentage runs first because it appears first in the array, and PHP preserves insertion order for associative arrays, so the output is stable every run.
That ordering, though, is the real flaw hiding in this otherwise tidy code. The rules run in whatever order they were registered, and each sees the total left by the rule before it, so the final price depends on registration order: apply the flat coupon before the percentage and the customer pays a different amount. The code treats array insertion order as if it were deliberate business policy, when nothing in it says the order was ever a decision. A second, quieter problem is that percentOff uses intdiv, silently truncating fractional cents in the shop's favour on odd totals -- defensible as a rounding rule, but only if someone actually chose it rather than inheriting it from the operator. A robust engine would make both the ordering and the rounding explicit and tested, not accidental properties of how the list happened to be built.
Common Mistakes
- Expecting
use ($x)to see later changes. The value is packed when the closure is defined, not when it is called. Reassigning the outer variable afterwards has no effect on what the closure already captured.
- Expecting
use (&$x)to be a private copy. By reference means the closure and the caller share one variable. Writes inside the closure leak out, and outside changes leak in; that is the point, but it surprises people who wanted isolation.
- Forgetting the
useclause entirely. An anonymous function does not automatically see outer variables the way an arrow function does. Withoutuse ($x), the name$xis simply undefined inside the closure body, and understrict_typesyou get an error rather than a silentnull.
- Capturing a loop variable by reference and reusing it. Writing
use (&$i)inside a loop, or reusing aforeachreference variable, leaves a live link that every later iteration overwrites, so all the closures end up sharing the loop's final value.
- Reaching for a closure when a named function is clearer. If a function captures nothing and is reused in several places, a plain named function documents intent better and is easier to test than an anonymous one buried in a variable.
- Cramming statements into an arrow function.
fnbodies are a single expression. Trying to sneak in multiple steps with commas or nested ternaries produces code that is far harder to read than thefunction () use (...) { ... }form it should have been.
- Assuming an arrow function captures by reference. Arrow functions only ever capture by value. If you need to write back to an outer variable, you must use the long form with
use (&$x); there is no reference mode forfn.
- Rebinding closures to break encapsulation.
Closure::bindcan hand a closure access to another object's private members. Used outside framework internals it quietly defeats the access modifiers the class author chose, and the coupling it creates is invisible at the call site.
- Leaking large captured values. A closure keeps its captured variables alive as long as the closure itself lives. Capturing a big array or an object graph by value, then storing the closure in a long-lived registry, holds all of that memory far longer than expected.
Best Practices
- Prefer capture by value; it keeps closures predictable. Reach for
use (&$x)only when sharing state back to the caller is genuinely the design you want.
- Use arrow functions for short, one-expression callbacks passed to
array_map,array_filter,usort, and similar. Their automatic capture pays off precisely when the body is tiny.
- Use the long
function () use (...) {}form when the body needs several statements or when you want to name captures explicitly for the reader.
- Type-hint closure parameters and return types just as you would a named function. Closures are not an excuse to drop the type declarations that catch mistakes early.
- Keep the list of captured variables short. A closure that packs many variables is usually a sign that a small class with named properties would be clearer.
- When a closure captures
$this, be conscious that it now keeps the whole object alive; unset or avoid storing such closures in long-lived structures.
- Name the variable that holds a closure for what it does (
$formatRow,$isEligible), not for the fact that it is a function.
- Document any reference capture with a short comment. The single
&is easy to miss, and readers need to know that state is shared.
Practice Exercises
- Write a function
makeCounter(): callablethat returns a closure capturing a private count by reference, so that each call to the returned closure returns the next integer starting at 1. Create two independent counters and show they do not interfere.
- Given an array of product prices in cents, use
array_mapwith an arrow function to apply a 20 percent markup, thenarray_filterwith another arrow function to keep only the results above 5000 cents. Print the surviving prices formatted as dollars.
- Build a small pipeline: an array of closures that each take a string and return a transformed string (trim, lowercase, replace spaces with hyphens). Write a
pipefunction that folds an input through all of them in order and returns the final slug.
- Extend the discount engine so the order of rules is explicit rather than accidental: give each rule a numeric priority, sort the rules by it before applying, and add a test that proves swapping two rules' priorities changes the total as expected.