Computer >> Computer tutorials >  >> Programming >> PHP

Access variables from parent scope in anonymous PHP function


The ‘use’ keyword can be used to bind variables into the specific function’s scope.

Use the use keyword to bind variables into the function's scope −

Example

<?php
$message = 'hello there';
$example = function () {
   var_dump($message);
};
$example();
$example = function () use ($message) { // Inherit $message
   var_dump($message);
};
$example();
// Inherited variable's value is from when the function is defined, not when called
$message = 'Inherited value';
$example();
$message = 'reset to hello'; //message is reset
$example = function () use (&$message) { // Inherit by-reference
   var_dump($message);
};
$example();
// The changed value in the parent scope
// is reflected inside the function call
$message = 'change reflected in parent scope';
$example();
$example("hello message");
?>

Output

This will produce the following output −

NULL string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "change reflected in parent scope" string(32) "change reflected in parent scope"

Originally, the ‘example’ function is called first. Second time, $message is inherited, and its value is changed when the function was defined. The value of $message is reset and inherited again. Since the value was changed in the root/parent scope, the changes are reflected when the function is called.