I've been writing some code for PHP 5.3, and I wanted to do something similar to the code I'm showing below. I expect this code to print 'hellohello', but it prints 'hello' instead, and an error.
It appears the $inner closure does not have access to the outer function's parameters. Is this normal behavior? Is it a PHP bug? I can't see how that could be considered correct behavior...
<?php
function outer($var) {
print $var;
$inner = function() {
print $var;开发者_StackOverflow中文版
};
$inner();
}
outer('hello');
Thanks!
You need to use the use
keyword. See this for more details.
Wikipedia has some explanation of this:
function getAdder($x)
{
return function ($y) use ($x) {
return $x + $y;
};
}
$adder = getAdder(8);
echo $adder(2); // prints "10"
Here, getAdder() function creates a closure using parameter $x (keyword "use" forces getting variable from context), which takes additional argument $y and returns it to the caller.
So, to make your example work the way you want it to:
<?php
function outer($var) {
print $var;
$inner = function() use ($var) {
print $var;
};
$inner();
}
outer('hello');
I would guess that the $inner function doesn't have the scope to access $var
Try this
function outer($var) {
print $var;
$inner = function($var) {
print $var;
};
$inner($var);
}
outer('hello');
精彩评论