tags:

views:

75

answers:

2

I'm trying to pass a parameter from a parent function to a child function while keeping the child function parameterless. I tried the following but it doesn't seem to work.

public static function parent($param)
{
    function child()
    {
        global $param;

        print($param) // prints nothing
    }
}
+3  A: 

You can use lambda functions from PHP 5.3 and on:

public static function parent($param) {
  $child = function($param) {
    print($param);
  }

  $child($param);
}

If you need to do it with earlier versions of PHP try create_function.

halfdan
+1 Starting with PHP 5.3, he can even use [closures](http://php.net/manual/en/functions.anonymous.php) so he doesn't need to explicitly pass `$param`. That comes pretty close to what he's looking for I think
Pekka
+1  A: 

I think that the global you call in child() does not refer to that scope. Try running it with really global variable.

Tomasz Kowalczyk
The global in child() does not belong to the scope of the parent() function but to the real global scope.
halfdan
I was thinking exactly this way - if he declares variable in parent function and then is trying to access it throught global in child - there is no chance.
Tomasz Kowalczyk