CKTIS / PHP
Capturing a variable by reference in a PHP closure: `use (&$carry)`
With `use (&$carry)`, a closure and its defining scope can read and update the same variable. Without `&`, the closure captures the value at creation time.
Version: PHP 8.3; extension availability may vary
Syntax
$carry = 0;
$add = function (int $item) use (&$carry): void {
$carry += $item;
};In PHP 8.3, closure capture by reference use (&$carry) means placing use (&$carry) after an anonymous function’s parameter list and before any return type. The & makes both occurrences of $carry refer to the same variable content. Assigning on either side is visible on the other. The closure captures from where it is defined, not where it is called. $carry is an ordinary variable name, not a keyword.
use ($carry) captures the value at creation time: later assignments to an outer integer do not change what the closure reads. An arrow function (fn) captures automatically by value. This use clause is not a namespace import. It is also distinct from a by-reference parameter (function (&$carry)) or a by-reference return (function &()). The use list cannot contain $this, superglobals, or a name already used as a parameter.
Initialize $carry before creating the closure. The closure can retain access to the captured state after its defining function returns. Calling unset($carry) outside the closure removes that outer binding, not the state the closure still holds; assigning to the name again does not restore the binding. Use references when shared mutable state is intentional: the call expression alone does not show that the closure updates $carry, but the updated value can be read from the outer $carry after the call.
The $carry callback parameter in array_reduce() is different: it receives the initial value and then the previous callback’s return value on subsequent iterations. For a straightforward reduction, return the updated accumulator instead of capturing an outer variable. The use (&$carry) syntax itself requires no additional extension.
Examples
<?php
$carry = 0;
$snapshot = function () use ($carry): int {
return $carry;
};
$add = function (int $item) use (&$carry): void {
$carry += $item;
};
$add(2);
echo $carry, "\n";
$carry += 10;
$add(3);
echo $snapshot(), "\n", $carry, "\n";
Result
2 0 15
`$add(2)` changes the outer `$carry` to `2`. After the outer code adds `10`, `$add(3)` reads `12` and writes `15`. `$snapshot()` still returns `0` because it captured the value at creation.
Related lessons
- PHP · Lesson 15 · Advanced · Version: 2