在学习
PHP中的匿名函数时,我遇到了这个问题:
Anonymous functions can use the variables defined in their enclosing
scope using the use syntax.
例如:
$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);
}
);
为什么我不能像以下一样将$useRandom全局化?
$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);
}
);
这两种方法有什么区别?