PHP:传递匿名函数作为参数

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,而不是我想要的结果.我明白,我在技术上合格的对象实例ClosuremyFunction,不过,我一定附近,我已经看到了这个在其他地方完成.这可能吗?如果是这样,我做错了什么?

为了便于讨论,我无法修改我传递闭包的函数.

tl; dr:如何将匿名函数声明作为参数传递,从而导致返回值作为参数传递.

PS:如果不清楚,所需的输出是:

Array
(
    [fruit] => apple
    [vegetable] => broccoli
    [other] => canned soup
)
Run Code Online (Sandbox Code Playgroud)

irc*_*ell 9

你不能.你必须先调用它.由于PHP不支持闭包解引用,因此您必须先将其存储在变量中:

$f = function(){
    $data = array(
        'fruit'     => 'apple',
        'vegetable' => 'broccoli',
        'other'     => 'canned soup');
    return $data;
};
myfunction($f());
Run Code Online (Sandbox Code Playgroud)

  • 几年后...... [有可能](http://php.net/manual/en/functions.anonymous.php) (10认同)

Pav*_*ari 9

最近,我正在解决类似的问题,所以我发布了我的代码,它按预期工作:

$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:回答感谢这个答案: 答案


Cro*_*zin 5

您传递的是函数本身,而不是您注意到的结果。您必须立即执行该函数,如下所示:

myFunction((function() {
    return ...;
})(), $otherArgs);
Run Code Online (Sandbox Code Playgroud)

PHP 不支持这样的事情,所以你被迫将该函数分配给某个变量并执行它:

$func = function() { ... };
myFunction($func(), $otherArgs);
Run Code Online (Sandbox Code Playgroud)

  • 真的吗?我们是否必须继续如此频繁地诋毁 PHP(说它很糟糕,而不是指出它的不足)?这么多仇恨...如果你认为它很糟糕,那很好。克服它... (14认同)