kmd*_*hrm 5 php closures scope anonymous-function
以下两种在闭包中访问全局变量的情况之间是否存在任何性能或其他差异:
情况1:
$closure = function() use ($global_variable) {
// Use $global_variable to do something.
}
Run Code Online (Sandbox Code Playgroud)
案例2:
$closure = function() {
global $global_variable;
// Use $global_variable to do something.
}
Run Code Online (Sandbox Code Playgroud)
sim*_*mon 11
您的两个示例之间存在重要差异:
$global_variable = 1;
$closure = function() use ($global_variable) {
return $global_variable;
};
$closure2 = function() {
global $global_variable;
return $global_variable;
};
$global_variable = 99;
echo $closure(); // this will show 1
echo $closure2(); // this will show 99
Run Code Online (Sandbox Code Playgroud)
use获取$global_variable闭包定义期间的值,同时global获取$global_variable执行期间的当前值.
globaluse从父作用域继承变量时从全局作用域继承变量.
| 归档时间: |
|
| 查看次数: |
870 次 |
| 最近记录: |