Php is_function () to determine if a variable is a function

I was very pleased to read anonymous functions in php that allow you to declare a variable which is a function easier than you could do with create_function . Now I am wondering if I have a function that is passed to a variable, how can I check it to determine if it is a function? The is_function () function does not exist yet, and when I make var_dump a variable, which is a function ::

$func = function(){ echo 'asdf'; }; var_dump($func); 

I get this:

 object(Closure)#8 (0) { } 

Any thoughts on how to check if this is a function?

+67
php anonymous-function
May 14 '10 at 16:03
source share
4 answers

Use is_callable to determine if a given variable is a function. For example:

 $func = function() { echo 'asdf'; }; if( is_callable( $func ) ) { // Will be true. } 
+106
May 14, '10 at 16:09
source share

You can use function_exists to check if there is a function with the given name. And to combine this with anonymous functions, try the following:

 function is_function($f) { return (is_string($f) && function_exists($f)) || (is_object($f) && ($f instanceof Closure)); } 
+28
May 14 '10 at 16:05
source share

If you want to check if a variable is an anonymous function and not a callable string or array, use instanceof .

 $func = function() { echo 'asdf'; }; if($func instanceof Closure) { // Will be true. } 

Anonymous functions (such as those added in PHP 5.3) are always instances of the Closure class, and each instance of the Closure class is an anonymous function.

In PHP there is another type of thing that can be considered a function, and those objects that implement the __invoke magic method. If you want to include them (while excluding strings and arrays), use method_exists($func, '__invoke') . This will include closures anyway, since closures implement __invoke for consistency.

+16
Dec 12 '14 at 23:50
source share
 function is_function($f) { return is_callable($f) && !is_string($f); } 
0
Sep 27 '17 at 12:03 on
source share



All Articles