PHP-'use()'或'global'访问闭包中的全局变量之间的区别? [英] PHP - Difference between 'use()' or 'global' to access a global variable in a closure?
本文介绍了PHP-'use()'或'global'访问闭包中的全局变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下两种访问闭包中的全局变量的情况之间,性能是否存在任何差异?
Is there any kind of performance or other difference between following two cases of accessing a global variable in a closure:
案例1:
$closure = function() use ($global_variable) {
// Use $global_variable to do something.
}
案例2:
$closure = function() {
global $global_variable;
// Use $global_variable to do something.
}
推荐答案
您的两个示例之间有一个重要区别:
There is an important difference between your two examples:
$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
use
在闭包定义期间采用$global_variable
的值,而global
在执行期间采用$global_variable
的当前值.
use
takes the value of $global_variable
during the definition of the closure while global
takes the current value of $global_variable
during execution.
global
从全局范围继承变量,而use
从父范围继承.
global
inherits variables from the global scope while use
inherits them from the parent scope.
这篇关于PHP-'use()'或'global'访问闭包中的全局变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文