In PHP, you have to use the global
keyword in order to access a variable from the global scope when inside of a function. However, how can you access a
variable within the scope of a parent function?
function foo() {
$content = 'foobar';
function bar() {
echo $content; // echos nothing
}
}
How can I access the $content
variable?
You have two options:
Give $content
as a parameter
function foo() {
$content = 'foobar';
function bar($content) {
echo $content . '1'; // 'foobar1'
}
bar();
}
foo();
Use closures (PHP Manual) (PHP 5.3.0+)
Please note that the function declaration is a bit different compared to the 'conventional way' of declaring functions.
function foo() {
$content = 'foobar';
$bar = function() use ($content) {
echo $content . '1';
}; // <-- As it's an assignment, end with a ';'
$bar();
}
foo(); // 'foobar1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With