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<的当前值/code> 执行期间.
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屋!
查看全文