2012-08-12 142 views
3

简单的问题,但艰难的答案?我在类方法中有以下匿名函数:在匿名函数中调用匿名函数(初始)

$unnest_array = function($nested, $key) { 
    $unnested = array(); 

    foreach ($nested as $value) { 
     $unnested[] = (object) $value[$key]; 
    } 

    return $unnested; 
}; 

在同一个类方法中,我有这个数组,我保存了匿名函数。即我使用内联create_function()创建了一个新的匿名函数,我想要使用已定义的匿名函数$unnest_array()。可能吗?

$this->_funcs = array(
    'directors' => array(
     'func' => create_function('$directors', 'return $unnest_array($directors, "director");'), 
     'args' => array('directors') 
    ) 
); 

此刻我得到“Undefined variable:unnest_array”。帮帮我?

+1

您可能想将其称为“关闭”并删除所有内容。 – 2012-08-12 19:04:18

+0

[php.net](http://php.net/manual/en/functions.anonymous.php)将其称为匿名函数以及闭包。为什么要删除一切 – Viktor 2012-08-12 22:04:15

+0

加1即使只是为了开始部分:D – Bakaburg 2012-09-05 00:32:31

回答

2

为什么您首先使用create_function?完全替代create_function的闭包,在5.3之后的所有版本的PHP中都基本废弃了。看起来你试图partially apply$unnest_array固定第二个参数为"director"

除非我误解了你,你应该能够通过使用关闭/匿名函数(未经测试),以达到相同的结果:

$this->_funcs = array(
    'directors' => array(
     'func' => function($directors) use ($unnest_array) 
      { 
       return $unnest_array($directors, "director"); 
      }, 
     'args' => array('directors') 
    ) 
); 

use ($unnest_array)条款是需要访问父局部变量关闭的范围。

+2

小修正:'使用($ unnest_array)'而不是'使用$ unnest_array'。 – hakre 2012-08-12 19:07:53

+0

@hakra:谢谢,我的坏。自从我使用PHP以来已经有一段时间了! – 2012-08-12 19:10:47

+0

你完美的读完了我,谢谢!我没有意识到'使用'关键字。 – Viktor 2012-08-12 21:49:22