I have a problem in calling an anonymous method in another anonymous method.
<?php
$x = function($a)
{
return $a;
};
$y = function()
{
$b = $x("hello world a");
echo $b;
};
$y();
?>
Error:
Notice: Undefined variable: x in C:\xampp\htdocs\tsta.php on line 7
Fatal error: Function name must be a string in C:\xampp\htdocs\tsta.php on line 7
Add use
to your $y
function, then scope of $y
function will see $x
variable:
$y = function() use ($x){
$b = $x("hello world a");
echo $b;
};
You have to use anonymous function in same block.
<?php
$y = function(){
$x = function($a){
return $a;
};
$b = $x("hello world a");
echo $b;
};
$y();
Good Luck!!
Both @argobast and @hiren-raiyani answers are valid. The most generic one is the first, but the latter is more appropriate if the only consumer of the first anonymous function is the second one (ie $x is used only by $y).
Another option is (this one needs a change in the signature of the $y function) is to pass the anon. function as an argument to the function:
<?php
$x = function($a)
{
return $a;
};
$y = function(Closure $x)
{
$b = $x('hello world a');
echo $b;
};
$y($x);
This kind of "dependency injection" seems a bit cleaner to me instead of having a hidden dependency on $x with a 'use', but the choice is up to you.