Back to results for “Closures”
PHP › Closures & Anonymous Functions

How does passing a variable by reference into a closure's use clause differ from the default pass by value behavior?

Intermediate

Answer

By default, variables imported using the use keyword are captured by value, meaning the closure receives a snapshot of that variable's value at the time the closure was defined, and any changes made to that variable later, either inside or outside the closure, do not affect the other's copy, but adding an ampersand before the variable name in the use clause captures it by reference instead, meaning changes made inside the closure directly affect the original outside variable, and vice versa.
$counter = 0;
$increment = function () use (&$counter) {
    $counter++;
};
$increment();
$increment();
echo $counter;
Real-world example A simple counter utility uses a closure that captures a shared counter variable by reference, allowing repeated calls to the closure to consistently increment the exact same underlying counter value across multiple invocations.

Common follow-ups: Why would a developer choose pass by reference over pass by value for a closure's use variable?;Are there any risks associated with capturing variables by reference in a closure?