我们来检查一个对象里的方法是否存在的时候,对于method_exists()函数很常见,比如:
<?php
if (method_exists($object, 'SomeMethod')) {
$object->SomeMethod($this, TRUE);
}
?>
method_exists()函数没有检测$object对象的方法对于当前的运行环境是可见性,如果有,就返回TRUE,如果没有,就返回FALSE.
如果当你恰好判断一个私有或者受保护的方法时,你能够得到一个正确的返回,但是执行的时候,会得到一个“Fatal Error”错误警告。
这时候is_callable()函数会对于可见性进行考虑,is_callable()函数接收一个回调参数,可以指定一个函数名称或者一个包含方法名和对象的数组,如果在当前作用域中可以执行,就返回TRUE。
<?php
if (is_callable(array($object, 'SomeMethod'))) {
$object->SomeMethod($this, TRUE);
}?>
下面代码举例子说明两个的区别:
<?php
class Test {
public function PublicMethod(){}
protected function ProtectedMethod(){}
private function PrivateMethod(){}
public static function PublicStaticMethod(){}
public static function ProtectedStaticMethod(){}
private static function PrivateStaticMethod(){}
}
$test = new Test();
$callbacks = array(
array($test, 'PublicMethod'),
array($test, 'ProtectedMethod'),
array($test, 'PrivateMethod'),
array($test, 'PublicStaticMethod'),
array($test, 'ProtectedStaticMethod'),
array($test, 'PrivateStaticMethod'),
array('Test', 'PublicMethod'),
array('Test', 'ProtectedMethod'),
array('Test', 'PrivateMethod'),
array('Test', 'PublicStaticMethod'),
array('Test', 'ProtectedStaticMethod'),
array('Test', 'PrivateStaticMethod'),
);
foreach ($callbacks as $callback){
var_dump($callback);
var_dump(method_exists($callback[0], $callback[1]));
var_dump(is_callable($callback));
echo '<hr />';
}
运行结果
array(2) { [0]=> object(Test)#2 (0) { } [1]=> string(12) "PublicMethod" } bool(true) bool(true)
array(2) { [0]=> object(Test)#2 (0) { } [1]=> string(15) "ProtectedMethod" } bool(true) bool(false)
array(2) { [0]=> object(Test)#2 (0) { } [1]=> string(13) "PrivateMethod" } bool(true) bool(false)
array(2) { [0]=> object(Test)#2 (0) { } [1]=> string(18) "PublicStaticMethod" } bool(true) bool(true)
array(2) { [0]=> object(Test)#2 (0) { } [1]=> string(21) "ProtectedStaticMethod" } bool(true) bool(true)
array(2) { [0]=> object(Test)#2 (0) { } [1]=> string(19) "PrivateStaticMethod" } bool(true) bool(false)
array(2) { [0]=> string(4) "Test" [1]=> string(12) "PublicMethod" } bool(true) bool(true)
array(2) { [0]=> string(4) "Test" [1]=> string(15) "ProtectedMethod" } bool(true) bool(false)
array(2) { [0]=> string(4) "Test" [1]=> string(13) "PrivateMethod" } bool(true) bool(false)
array(2) { [0]=> string(4) "Test" [1]=> string(18) "PublicStaticMethod" } bool(true) bool(true)
array(2) { [0]=> string(4) "Test" [1]=> string(21) "ProtectedStaticMethod" } bool(true) bool(true)
array(2) { [0]=> string(4) "Test" [1]=> string(19) "PrivateStaticMethod" } bool(true) bool(false)
is_callable()还有其他的用法,例如,不检查所提供的类或方法,只检查函数或方法的语法是否正确。像method_exists()一样,is_callable()可以触发类的自动加载。
如果一个对象存在魔术方法__call,在进行方法判断时method_exists()会返回FALSE,而is_callable()会返回TRUE。
'; } } $obj = new MethodTest(); $obj->runtest('in object context'); var_dump(method_exists($obj,'runtest')); var_dump(is_callable(array($obj,'runtest'))); echo ''; ?>
运行结果
Calling object method runtest in object context
bool(false) bool(true)