Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
}
like image 929
kmdhrm Avatar asked Sep 28 '16 08:09

kmdhrm


People also ask

What is difference between global and GLOBALS in PHP?

They are two different things. global is a keyword which tells that the variable is from a global scope. E.g. if you're about to access a variable inside a function that's defined outside you'll need to use the global keyword to make it accessible in the function. $GLOBALS is a superglobal array.

What is $_ global in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

What is difference between static and global variable in PHP?

Global is used to get the global vars which may be defined in other scripts, or not in the same scope. e.g. Static is used to define an var which has whole script life, and init only once.

Can functions access global variables PHP?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.


2 Answers

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.

like image 170
simon Avatar answered Nov 02 '22 23:11

simon


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.

like image 32
Gectou4 Avatar answered Nov 03 '22 00:11

Gectou4