I'm passing a variable into anonymous function (closure) via use
, and within the closure body I'm modifying the variables value:
$myVar = false;
$myAnonFunc = function() use ($myVar) {
$myVar = true;
};
$myAnonFunc();
echo '$myVar => ' . ($myVar ? 'TRUE' : 'FALSE') . PHP_EOL;
// Expected `$myVar => TRUE` but got `$myVar => FALSE`
I'm expecting $myVar
within the closure to be bound to the $myVar
in the parent scope, such that changes to the $myVar
variable within the closure are reflected in the parent. This doesn't appear to be happening. How is understanding of PHP closures incorrect and what should my expectation be? How can actually do what I want?