is_callable — 验证变量的内容是否能够进行函数调用
语法:
bool is_callable ( mixed $var [, bool $syntax_only [, string $callable_name ]] )
验证变量的内容是否能够进行函数调用。可以用于检查一个变量是否包含一个有效的函数名称,或者一个包含经过合适编码的函数和成员函数名的数组。
name
既可以是一个字符串类型的函数名称,也可以是一个对象和成员函数名的组合数组,比如:array($SomeOject, 'MethodName')
如果设置为true,那么只是验证name是一个函数或者方法,函数仅仅会拒绝不是字符串,亦或是结构不合法的数组作为回调函数。合法结构是指一个包含两个成员的数组,第一个是对象或者字符串,第二个是一个字符串。
接收“调用名称”,在下面的例子里它是“someClass::someMethod"。请注意尽管someClass::someMethod()是一个可调用的静态方法,但是这里并不是真的表示一个静态方法
Return Values(返回值)
如果可调用返回true,否则返回false。
<?php
function doTimes($start, $end)
{
$start_time = explode (" ", $start);
$start_time = $start_time[1] + $start_time[0];
$end_time = explode (" ", $end);
$end_time = $end_time[1] + $end_time[0];
$time = $end_time - $start_time;
return $time;
}
class test
{
function test()
{
return true;
}
}
$test = new test;
$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
{
if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
}
$endIsCallable = microtime();
$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
{
if(method_exists('test', 'test')) { $existsIsTrue = true; }
}
$endExists = microtime();
$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists = doTimes($startExists, $endExists);
echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>method_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";
echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 method_exists in ".$timeExists." seconds";
?>
is_callable = TRUE, method_exists = TRUE
Did 10000 is_callables in 0.410346984863 seconds
Did 10000 method_exists in 0.175447940826 seconds
is_callable判断是回去调用__call魔术方法来判断,而method_exists不会