Dan*_*ugg 12 php closures anonymous-function argument-passing
是否可以将匿名函数作为参数传递,并让它立即执行,从而传递函数的return值?
function myFunction(Array $data){
print_r($data);
}
myFunction(function(){
$data = array(
'fruit' => 'apple',
'vegetable' => 'broccoli',
'other' => 'canned soup');
return $data;
});
Run Code Online (Sandbox Code Playgroud)
这会因Array类型提示而引发错误,抱怨传递的对象.好吧,如果我删除类型提示,它当然会吐出Closure Object,而不是我想要的结果.我明白,我在技术上合格的对象实例Closure来myFunction,不过,我一定附近,我已经看到了这个在其他地方完成.这可能吗?如果是这样,我做错了什么?
为了便于讨论,我无法修改我传递闭包的函数.
tl; dr:如何将匿名函数声明作为参数传递,从而导致返回值作为参数传递.
PS:如果不清楚,所需的输出是:
Array
(
[fruit] => apple
[vegetable] => broccoli
[other] => canned soup
)
Run Code Online (Sandbox Code Playgroud)
你不能.你必须先调用它.由于PHP不支持闭包解引用,因此您必须先将其存储在变量中:
$f = function(){
$data = array(
'fruit' => 'apple',
'vegetable' => 'broccoli',
'other' => 'canned soup');
return $data;
};
myfunction($f());
Run Code Online (Sandbox Code Playgroud)
最近,我正在解决类似的问题,所以我发布了我的代码,它按预期工作:
$test_funkce = function ($value)
{
return ($value + 10);
};
function Volej($funkce, $hodnota)
{
return $funkce->__invoke($hodnota);
//or alternative syntax
return call_user_func($funkce, $hodnota);
}
echo Volej($test_funkce,10); //prints 20
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.首先,我创建闭包,然后接受闭包和参数的函数,并调用其内部并返回其值.够了.
PS:回答感谢这个答案: 答案
您传递的是函数本身,而不是您注意到的结果。您必须立即执行该函数,如下所示:
myFunction((function() {
return ...;
})(), $otherArgs);
Run Code Online (Sandbox Code Playgroud)
PHP 不支持这样的事情,所以你被迫将该函数分配给某个变量并执行它:
$func = function() { ... };
myFunction($func(), $otherArgs);
Run Code Online (Sandbox Code Playgroud)