在匿名函数中调用匿名函数(初始)
问题描述:
简单的问题,但艰难的答案?我在类方法中有以下匿名函数:在匿名函数中调用匿名函数(初始)
$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”。帮帮我?
答
为什么您首先使用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)
条款是需要访问父局部变量关闭的范围。
您可能想将其称为“关闭”并删除所有内容。 – 2012-08-12 19:04:18
[php.net](http://php.net/manual/en/functions.anonymous.php)将其称为匿名函数以及闭包。为什么要删除一切 – Viktor 2012-08-12 22:04:15
加1即使只是为了开始部分:D – Bakaburg 2012-09-05 00:32:31