Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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

 Live Demo

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

Updated on: 2020-04-09T13:43:42+05:30

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements