Junior — Middle
How to pass a value from an outer scope into a closure for its use inside?
sobes.tech AI
Answer from AI
In PHP, the keyword use is used to pass a value from an external scope into a closure. It allows capturing variables from the external context and using them inside an anonymous function.
Example:
$externalVar = 10;
$closure = function() use ($externalVar) {
echo $externalVar;
};
$closure(); // Outputs 10
If you need to modify the variable's value inside the closure, you should pass it by reference:
$count = 0;
$increment = function() use (&$count) {
$count++;
};
$increment();
$increment();
echo $count; // Outputs 2