views:

35

answers:

2

Hi, 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!

A: 
Tom Gullen
+3  A: 

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');
Skilldrick
Thank you, Sir. That is pretty nasty!
cha0s