Reputation: 35265
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
}
}
Upvotes: 1
Views: 1549
Reputation: 4869
The right way to do this there would be to create an anonymous function inside your parent function, and then use the ''use'' keyword.
public static function parent($params) {
function() use ($params) {
print($params);
}
}
https://www.php.net/manual/en/functions.anonymous.php
Upvotes: 1
Reputation: 10467
I think that the global you call in child()
does not refer to that scope. Try running it with really global variable.
Upvotes: 1
Reputation: 34234
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.
Upvotes: 3