Is it possible to access outer local varialbe in a PHP sub-function?
In below code, I want to access variable $l
in inner function bar. Declaring $l
as global $l
in bar doesn't work.
function foo()
{
$l = "xyz";
function bar()
{
echo $l;
}
bar();
}
foo();
You must use the
use
keyword.In the very very old PHP 5.2 and earlier this didn't work. The syntax you've got isn't a closure, but a definition of a global function.
works the same as:
If you execute function
foo
twice, PHP will complain that you've tried to re-define a (global) functionbar
.You could probably use a Closure, to do just that...
Edit : took some time to remember the syntax, but here's what it would look like :
And, running the script, you'd get :
A couple of note :
;
after the function's declaration !use
the variable by reference, with a&
before it's name :use (& $l)
For more informations, as a reference, you can take a look at this page in the manual : Anonymous functions
You can read default value by:
If You would use two functons in the same time - it's like someone's using a spoon and You want to take a food from that spoon - You'll waste a food or some of You will starv. Anyway - You would have to set a pointer somehow in a hard way. It's impossible to get any field from other function or class without calling it to life. Functions/methods are instance-like - they need to be called.
Share the common fields by accessing a global fields with synchronized functions.