Closures

suggest change

An anonymous function does not automatically see variables from the parent scope.

The function has its own scope. Parent-scope variables are not local variables inside it.

$externalVariable = "Hello";
$secondExternalVariable = "Foo"; 
$myFunction = function() { 
  
  var_dump($externalVariable, $secondExternalVariable); // Warning: undefined variables (a notice before PHP 8) 

};

It cannot see those variables unless you import them with use:

$myFunction = function() use($externalVariable, $secondExternalVariable) {
   var_dump($externalVariable, $secondExternalVariable); // string(5) "Hello", string(3) "Foo"
};

This follows PHP's function scope: a variable that is not local, not imported with use, and not declared global is not defined in the function.

Also note:

Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing.

The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Taken from the PHP Documentation for Anonymous Functions


By default, use imports the value the variable had when the closure was created (early binding).

To change this behavior you should pass the variable by-reference.

$rate = .05;

// Exports variable to closure's scope
$calculateTax = function ($value) use ($rate) {
    return $value * $rate;
};

$rate = .1; 

print $calculateTax(100); // 5
$rate = .05;

// Exports variable to closure's scope
$calculateTax = function ($value) use (&$rate) { // notice the & before $rate
    return $value * $rate;
};

$rate = .1;

print $calculateTax(100); // 10

Call the closure like any other function:

$message = "I'm yelling at you";

$yell = function() use($message) {
    echo strtoupper($message);
};

$yell(); // I'M YELLING AT YOU

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents