Counter closure with by-reference capture
Write a function builder that takes an integer and returns a closure. Each call to the returned closure adds its argument to the running total and returns the new total, so state persists across calls.
<?php
$a = builder(5);
echo $a(3); // 8
echo $a(1); // 9
function builder(int $in) {
// your code here
}
Write the implementation.
Return an anonymous function that captures $in by reference via use (&$in). By-reference capture lets the closure mutate the same variable across calls, so the running total persists. Without &, each call would start from the original $in because the value is copied at definition time.
- ✗Capturing by value (
use ($in)) and expecting the total to persist between calls - ✗Believing PHP closures auto-bind the outer scope like JavaScript, without an explicit
use - ✗Confusing a by-reference
use (&$in)with astaticvariable inside the closure
- →How does
use ($in)differ fromuse (&$in)at the moment the closure is defined? - →What does the arrow-function syntax
fn() =>capture automatically, and by value or reference?
A closure captures outer variables explicitly via use. By default the capture is by value — a copy is taken at the moment the closure is defined, and later changes to the outer variable are not visible.
<?php
function builder(int $in) {
return function (int $i) use (&$in) {
$in += $i; // mutate the same variable
return $in;
};
}
$a = builder(5);
echo $a(3); // 8
echo $a(1); // 9
echo $a(4); // 13
The key detail is the & in use (&$in). Without it each call would start from the original copy 5 and the total would not accumulate. Arrow functions (fn() =>) capture variables automatically and always by value.