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.