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

PhpAnonymous Function

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.
}

Solution 2 - Php

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

Solution 3 - Php

If you only want to check whether 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 (of the kind that were added in PHP 5.3) are always instances of the Closure class, and every instance of the Closure class is an anonymous function.

There's another type of thing in PHP that could arguably be considered a function, and that's objects that implement the __invoke magic method. If you want to include those (while still excluding strings and arrays), use method_exists($func, '__invoke'). This will still include closures, since closures implement __invoke for consistency.

Solution 4 - Php

function is_function($f) {
    return is_callable($f) && !is_string($f);
}

Solution 5 - Php

In php valid callables can be functions, name of functions (strings) and arrays of the forms ['className', 'staticMethod'] or [$object, 'method'], so to detect only functions need to exclude strings and arrays:

function isFunction($callable) {
    return $callable && !is_string($callable) && !is_array($callable) && is_callable($callable);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJageView Question on Stackoverflow
Solution 1 - PhpJon BenedictoView Answer on Stackoverflow
Solution 2 - PhpGumboView Answer on Stackoverflow
Solution 3 - PhpBrilliandView Answer on Stackoverflow
Solution 4 - PhpArtemiy StagnantIce AlexeewView Answer on Stackoverflow
Solution 5 - PhpAndrey IzmanView Answer on Stackoverflow