phpscopeclosuresanonymous-function

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.
}

Solution

  • 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.