PHP: Pass anonymous function as argument

為{幸葍}努か 提交于 2019-12-04 00:53:19

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());
Pavel Hanpari

Recently, I was solving similar problem so I am posting my code which is working as expected:

$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

Hope it helps. First, I am creating closure, then function which accepts closure and argument and is invoking its inside and returning its value. Simply enough.

PS: Answered thanks to this answers: answers

Crozin

You're passing the function itself, not the results as you noticed. You'd have to execute that function immediately doing something like this:

myFunction((function() {
    return ...;
})(), $otherArgs);

PHP doesn't support such things, so you're forced to assign that function to some variable and execute it:

$func = function() { ... };
myFunction($func(), $otherArgs);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!