While learning about anonymous functions in PHP I came across this:
Anonymous functions can use the variables defined in their enclosing scope using the use syntax.
For example:
$test = array("hello", "there", "what's up");
$useRandom = "random";
$result = usort($test, function($a, $b) use ($useRandom){
if($useRandom=="random")
return rand(0,2) - 1;
else
return strlen($a) - strlen($b);
}
);
Why can't I just make $useRandom global like below?
$test2 = array("hello", "there", "what's up");
$useRandom = "random";
$result = usort($test, function($a, $b){
global $useRandom;
if($useRandom=="random")
return rand(0,2) - 1;
else
return strlen($a) - strlen($b);
}
);
What's the difference between these two approaches?