views:

284

answers:

2

I was pretty excited to read about anonymous functions in php, which let you declare a variable that is function easier than you could do with create_function. Now I am wondering if I have a function that is passed a variable, how can I check it to determine if it is a function? There is no is_function() function yet, and when I do a var_dump of a variable that 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?

+1  A: 

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

function is_function($f) {
    return (is_string($f) && function_exists($f)) || (is_object($f) && ($f instanceof Closure));
}
Gumbo
+6  A: 

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

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

if( is_callable( $func ) )
{
    // Will be true.
}
Jon Benedicto