bal*_*ant 6 php recursion anonymous-function php-5.5
我想调用一个匿名函数而不为它声明一个变量.
我知道这是一个有效的例子:
$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);
Run Code Online (Sandbox Code Playgroud)
但是我想自动调用它并取消它:
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);
Run Code Online (Sandbox Code Playgroud)
PS:我们假设这$input是以下数组:["Hello, ", "World!"].
那时,输出应该是:
Hello,
World!
Run Code Online (Sandbox Code Playgroud)
更新#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;
}()
Run Code Online (Sandbox Code Playgroud)
可以通过以下方式访问闭包debug_backtrace()and访问闭包使用像以前一样调用它__invoke()称呼它call_user_func():
$input = ["Hello, ", "World!"];
call_user_func(function ($bar) {
if (is_array($bar)) {
foreach ($bar AS $current) {
call_user_func(debug_backtrace()[1]['args'][0], $current));
}
}
else {
print($bar);
}
}, $input);
Run Code Online (Sandbox Code Playgroud)
但在我看来,将闭包分配给变量的第一个版本更具可读性,除了个人品味之外,我没有看到任何反对它的论据。
更新:它必须call_user_func()再次,而不是__invoke(),以便 args[0] 引用每个递归级别的闭包