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?
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.
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.
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.
YES! Anonymous functions are faster than regular functions.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With