Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Pass anonymous function as argument

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;
});

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: How can I pass an anonymous function declaration as an argument, resulting in the return value being passed as the argument.

PS: If not clear, the desired output is:

Array
(
    [fruit] => apple
    [vegetable] => broccoli
    [other] => canned soup
)
like image 626
Dan Lugg Avatar asked Nov 16 '10 21:11

Dan Lugg


2 Answers

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

like image 34
Pavel Hanpari Avatar answered Nov 07 '22 15:11

Pavel Hanpari


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());
like image 141
ircmaxell Avatar answered Nov 07 '22 15:11

ircmaxell