Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to check anonymous functions?

Tags:

function

php

Say that I have an array as follows:

array(
    [0] => function() { return "hello"; }
    [1] => function() { return "world"; }
    [2] => "look"
    [3] => function() { return "and";}
    [4] => function() { return "listen";}
)

Is there a way I can invoke 0, 1, 3 and 4 without invoking 2?

like image 641
elite5472 Avatar asked Jun 02 '12 11:06

elite5472


People also ask

How do you access anonymous functions?

An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression.

Can functions be anonymous?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

Do anonymous functions receive arguments?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

Are anonymous functions slower?

YES! Anonymous functions are faster than regular functions.


2 Answers

Anonymous functions are instances of the Closure class. So checking that and is_callable does the job.

foreach ($array as $func) {
    if (is_callable($func) && $func instanceof Closure) {
        $func();
    }
}

Actually, the class check should be enough since you cannot instantiate Closure objects manually except by creating an anonymous function.

like image 61
ThiefMaster Avatar answered Oct 18 '22 00:10

ThiefMaster


I think this is what you want. $result will be an array of the return value of each function call (except if it's not an anonymous function, in which case it will be the original value from $array).

$result = array_map(
                    function($e) {
                      return ($e instanceof Closure && is_callable($e)) ?
                        $e() : $e;
                    }, $array);
like image 29
Emil Vikström Avatar answered Oct 18 '22 00:10

Emil Vikström