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;
};
$inner();
}
outer('hello');
Thanks!
You need to use the
usekeyword. See this for more details.Wikipedia has some explanation of this:
So, to make your example work the way you want it to: