我想调用一个匿名函数,而不需要为其声明变量。
我知道这是可行的示例:
$foo = function ($bar) use ($foo) {
if (is_array($bar)) {
foreach ($bar AS $current) {
$foo($current);
}
}
else {
print($bar);
}
};
$foo($input);
# Unset variable cause we won't need it anymore
# and we like to have a lot of free memory.
unset($foo);
但我希望自动调用并取消它:
call_user_func(function ($bar) {
if (is_array($bar)) {
foreach ($bar AS $current) {
# This won't work
# as our function doesn't have any name.
call_user_func(__FUNCTION__, $current);
}
}
else {
print($bar);
}
}, $input);
但是这个例子不起作用,因为我们的函数没有名称。有解决方案吗?或者你知道任何解决这个问题的方法吗?
注:假设 $input
是以下数组:["Hello, ", "World!"]
。
因此,输出应该是:
Hello,
World!
更新 #1:
由于这只是一个示例,call_user_func_array(function () { ... }, $input)
不是我要找的解决方案。
如果我的 $input
是 [["Hello, ", "World"], "!"]
,它也无法正常工作。
更新 #2:
另一种我不想要的解决方案是 debug_backtrace()[1]['args'][0]->__invoke($current);
。我认为它只够用来进行 调试。:) 感谢@fschmengler。
还有另一种形式是 call_user_func(debug_backtrace()[1]['args'][0], $current));
。
更新 #3:
另外一种解决方案是由@UlrichEckhardt编写的,即将匿名函数嵌入到另一个匿名函数中。我认为,删除先前声明的函数变量 - 例如第一个示例 - 更加简洁、更短。但这也是一种解决方案。
function () {
$f = function ($param) use ($f) {
// use $f here
}
return $f;
}()
(function() {...})();
的解决方案可能很有趣,但现在并不实际。也许唯一可用的解决方案是对于 PHP 5.5 - 5.6 进行call_user_anonym_func()
的调用。 (?) - balintantunset()
删除它)。(虽然这并没有太多意义,但我认为这是一个有趣的问题。) - balintantarray_walk_recursive()
?它可以遍历嵌套数组的树,并在每个叶节点上调用一个函数。 - Ulrich Eckhardt