PHP - Difference between 'use()' or 'global' to access a global variable in a closure?

左心房为你撑大大i 提交于 2019-12-21 15:44:28

问题


Is there any kind of performance or other difference between following two cases of accessing a global variable in a closure:

Case 1:

$closure = function() use ($global_variable) {
  // Use $global_variable to do something.
}

Case 2:

$closure = function() {
  global $global_variable; 
  // Use $global_variable to do something.
}

回答1:


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 takes the value of $global_variable during the definition of the closure while global takes the current value of $global_variable during execution.

global inherits variables from the global scope while use inherits them from the parent scope.




回答2:


Usekeyword are in parent scope, while global and $GLOBALS are from everywhere.

That's mean if you use global you may not know if the value have changed, from where by what and what is the kind of the change.

You have more control by using use. So it depends on your needs.



来源:https://stackoverflow.com/questions/39741443/php-difference-between-use-or-global-to-access-a-global-variable-in-a-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!