一个匿名方法调用php中的另一个方法
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
我在另一个匿名方法中调用匿名方法时遇到问题。 p>
&lt;?php
$ x = function($ a)
{
返回$ a;
};
$ y = function()
{
$ b = $ x( “hello world a”);
echo $ b;
};
$ y();
?&gt;
code> pre>
错误: p>
注意:未定义的变量:C中的x:\ 第7行的xampp \ htdocs \ tsta.php p>
致命错误:第7行的C:\ xampp \ htdocs \ tsta.php中的函数名必须是字符串 p>
blockquote>
div>
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.