How the value change in parent scope reflects inside the closure?

An anonymous function usually does not inherit variables from it's parent scope. But it can inherit from it's parent scope using a keyword called use.

When the keyword use is used the closure inherits variable from the parent scope where it is defined not from where it is called.

It is possible to change the inherited variable's value from where the closure is called. The closure function can do so using inherit by reference. Lets consider a basic example.

Example

Normal parent scope variable inheritance using the keyword use. $param = 'PHP closure'; $writeMsg = function() use ($param) { echo $param; }; $param = 'PHP closure is bit different than JS closure'; $writeMsg();

Output

PHP closure
The above closure inherit the variable called param from where it is defined and not from where it is called. The variable param is reset just before the function closure call but it didn't effect inside of the closure definition. Inherit by reference would help us changing the param value from where it is called. Simply it needs to have the ampersand before the param where we are using the keyword use. See the code snippet below:
$param = 'PHP closure'; $writeMsg = function() use (&$param) { echo $param; }; $param = 'PHP closure is bit different than JS closure'; $writeMsg();

Output

PHP closure is bit different than JS closure

Comments