PHP:将匿名函数作为参数传递 [英] PHP: Pass anonymous function as argument
问题描述
是否可以将匿名函数作为参数传递并立即执行,从而传递函数的return
值?
Is it possible to pass an anonymous function as an argument, and have it execute immediately, thus passing the function's return
value?
function myFunction(Array $data){
print_r($data);
}
myFunction(function(){
$data = array(
'fruit' => 'apple',
'vegetable' => 'broccoli',
'other' => 'canned soup');
return $data;
});
由于Array
类型提示而引发错误,抱怨传递了一个对象.好吧,如果我删除了类型提示,它当然会弹出Closure Object
,而不是我想要的结果.我知道我在技术上将Closure
的对象实例传递给myFunction
,但是,我几乎可以肯定,我已经在其他地方看到了这一点.这可能吗?如果是这样,我在做什么错了?
This throws an error due to the Array
type-hint, complaining of an object being passed. Alright, if I remove the type-hint, it of course spits out Closure Object
, rather than the results I want. I understand that I am technically passing an object instance of Closure
to myFunction
, however, I'm near certain that I've seen this accomplished elsewhere. Is this possible? If so, what am I doing wrong?
为了便于讨论,我无法修改将闭包传递给的函数.
For the sake of this discussion, I cannot modify the function to which I'm passing the closure.
tl; dr:如何将匿名函数声明作为参数传递,导致将返回值作为参数传递.
PS:如果不清楚,则所需输出为:
PS: If not clear, the desired output is:
Array
(
[fruit] => apple
[vegetable] => broccoli
[other] => canned soup
)
推荐答案
您不能.您必须先调用它.而且由于PHP还不支持闭包解引用,因此您必须先将其存储在变量中:
You can't. You'd have to call it first. And since PHP doesn't support closure de-referencing yet, you'd have to store it in a variable first:
$f = function(){
$data = array(
'fruit' => 'apple',
'vegetable' => 'broccoli',
'other' => 'canned soup');
return $data;
};
myfunction($f());
这篇关于PHP:将匿名函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!