2015-08-13 218 views
2

我在调用另一个匿名方法的匿名方法时遇到问题。在另一个方法调用一个匿名方法在php

<?php 
    $x = function($a) 
    { 
     return $a; 
    }; 
    $y = function() 
    { 
     $b = $x("hello world a"); 
     echo $b; 
    }; 
    $y(); 
?> 

错误:

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

回答

4

添加use$y功能,然后$y功能的范围会看到$x变量:

$y = function() use ($x){ 
    $b = $x("hello world a"); 
    echo $b; 
}; 
+0

谢谢@arbogast,但如果在$ y返回几个没有。的数组,但我想访问只有特定的数组如何做到这一点?例如:var_dump($ y);和输出是:object(Closure)#3(2){[“static”] => array(3){[“a”] =>&array(2){[“foc”] => int(2), [“roc”] => int(4)} [“c”] =>&array(2){[“foc”] => int(2),[“roc”] => int(4)一个“] =>&数组(2){[”foc“] => int(2),[”roc“] => int(4)}我访问数组'b'在我的情况。我希望你能够明白。谢谢 – Albertestein

+0

@Albertestein我不完全理解你。在你的示例函数中$ y不返回任何东西,没有返回语句,所以它默认返回NULL。 – arbogastes

+0

对不起,兄弟我在代码中做了一些更改,我提到了这一点。<?php $ arr = array(1,2,3,4,5,6); ($ a)使用($ arr){ $ tst = $ arr [$ a]; return $ tst; }; $ y = function()use($ x){0} {0} {0} $ b = $ x(2); // echo $ b; }; $ y(); var_dump($ y);输出:object(Closure)#2(1){[“static”] => array(1){[“x”] => object(Closure)#1(2){[“static”] => array( 1){[“arr”] =>数组(6){[0] => int(1)[1] => int(2)[2] => int(3)[3] => int(4 (4)=> int(5)[5] => int(6)}} [“parameter”] => array(1){[“$ a”] => string(10)“”}}} } ... – Albertestein

-1

你有相同的块使用匿名函数。

<?php 

$y = function(){ 
    $x = function($a){ 
     return $a; 
    }; 
    $b = $x("hello world a"); 
    echo $b; 
}; 
$y(); 

祝您好运!

0

@argobast和@ungnn-raiyani答案都是有效的。最通用的是第一个,但如果第一个匿名函数的唯一使用者是第二个匿名函数的唯一使用者(即$ x仅用于$ y),则后者更合适。

另一种选择是(这个需要改变$ y函数的签名)是通过anon。函数作为参数传递给函数:

<?php 

$x = function($a) 
{ 
    return $a; 
}; 

$y = function(Closure $x) 
{ 
    $b = $x('hello world a'); 
    echo $b; 
}; 

$y($x); 

这种“依赖注入”的似乎有点清洁剂给我的,而不是具有与“使用”上$ X隐藏的依赖,但选择权在你。

相关问题