Access variables from parent scope in anonymous PHP function

PHPServer Side ProgrammingProgramming

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 −


 Live Demo

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


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.

Updated on 09-Apr-2020 13:43:42