Php is_function()来确定变量是否是函数

读到 php 中的 匿名函数时,我非常兴奋,因为它可以让您声明一个比使用 Create _ function 创建 _ 函数更容易的函数变量。现在我想知道,如果我有一个函数,传递一个变量,我如何检查它,以确定它是一个函数?现在还没有 is _ function ()函数,当我对一个变量执行 var _ dump 时,它是一个函数: :

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

我明白了:

object(Closure)#8 (0) { }

对于如何检查这是否是一个函数有什么想法吗?

48300 次浏览

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

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

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

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