A closure in PHP does not capture the enclosing scope automatically. Variables from outside are simply not there unless they are named in use, which is a deliberate choice — it makes the closure’s inputs explicit rather than accidental.
$rate = 0.18;
$withTax = function ($net) use ($rate) {
return $net * (1 + $rate);
};
$total = 0;
array_walk($lines, function ($line) use (&$total) {
$total += $line['net'];
});
The part that surprises people is that use ($rate) copies the value when the closure is defined, not when it is called — so changing $rate on the next line has no effect on anything the closure does afterwards. Prefixing with & captures by reference instead, which is how an accumulator like the one above works. One further limitation in 5.3: a closure created inside a method has no $this at all, so reaching the object means assigning it to a local first and passing that through use.