Reputation: 19
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
Upvotes: 2
Views: 80
Reputation: 361
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.
Upvotes: 0
Reputation: 1328
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;
};
Upvotes: 4
Reputation: 744
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!!
Upvotes: -1