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

泪湿孤枕 提交于 2019-11-29 21:59:57
Jon Benedicto

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

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

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.

function is_function($f) {
    return is_callable($f) && !is_string($f);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!