Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Access variables from parent scope in anonymous PHP function
In PHP, anonymous functions (closures) cannot access variables from the parent scope by default. The use keyword allows you to bind variables from the parent scope into the anonymous function's scope.
Syntax
The basic syntax for accessing parent scope variables in anonymous functions −
$variable = function() use ($parentVar) {
// Access $parentVar here
};
Example
Here's how to use the use keyword to access parent scope variables −
<?php
$message = 'hello there';
// Without 'use' - variable not accessible
$example = function () {
var_dump($message ?? 'undefined');
};
$example();
// With 'use' - inherit by value
$example = function () use ($message) {
var_dump($message);
};
$example();
// Value is captured when function is defined, not when called
$message = 'Inherited value';
$example(); // Still shows 'hello there'
// Using reference to get current value
$message = 'reset to hello';
$example = function () use (&$message) {
var_dump($message);
};
$example();
// Changes in parent scope are reflected
$message = 'change reflected in parent scope';
$example();
?>
The output of the above code is −
string(9) "undefined" string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "change reflected in parent scope"
Key Points
Understanding how variable inheritance works in closures −
-
By Value:
use ($var)copies the variable's value when the function is defined -
By Reference:
use (&$var)creates a reference to the original variable -
Multiple Variables:
use ($var1, $var2, &$var3)can inherit multiple variables
Conclusion
The use keyword is essential for accessing parent scope variables in PHP closures. Use by-value for static data and by-reference when you need live updates from the parent scope.
Advertisements
