PHP:将匿名函数作为参数传递 [英] PHP: Pass anonymous function as argument

查看:40
本文介绍了PHP:将匿名函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将匿名函数作为参数传递并使其立即执行,从而传递函数的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆