method_exists函数与is_callable函数

一、method_exists:检查类的方法是否存在
bool method_exists ( mixed $object , string $method_name )
参数:
object
对象示例或者类名。
method_name
方法名。
如果 method_name 所指的方法在 object 所指的对象类中已定义,则返回 TRUE,否则返回 FALSE。
案例:
<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>
输出:
bool(true)
二、is_callable :检测参数是否为合法的可调用结构

bool is_callable ( callable $name [, bool $syntax_only = false [, string &$callable_name ]] )
验证变量的内容能否作为函数调用。 这可以检查包含有效函数名的变量,或者一个数组,包含了正确编码的对象以及函数名。
参数:
name
要检查的回调函数。
syntax_only
如果设置为 TRUE,这个函数仅仅验证 name 可能是函数或方法。 它仅仅拒绝非字符,或者未包含能用于回调函数的有效结构。有效的应该包含两个元素,第一个是一个对象或者字符,第二个元素是个字符。
callable_name
接受“可调用的名称”。下面的例子是“someClass::someMethod”。 注意,尽管 someClass::SomeMethod() 的含义是可调用的静态方法,但例子的情况并不是这样的。
如果 name 可调用则返回 TRUE,否则返回 FALSE。
If the target class has __call() magic function implemented, then is_callable will ALWAYS return TRUE for whatever method you call it.
is_callable does not evaluate your internal logic inside __call() implementation (and this is for good).
Therefore every method name is callable for such classes.
Hence it is WRONG to say (as someone said):
...is_callable will correctly determine the existence of methods made with __call...
Example:
<?php
class TestCallable
{
    public function testing()
    {
          return "I am called.";
    }


    public function __call($name, $args)
    {
        if($name == 'testingOther') 
        {
                return call_user_func_array(array($this, 'testing'), $args);
        }
    }
}
$t = new TestCallable();
echo $t->testing();      // Output: I am called.
echo $t->testingOther(); // Output: I am called.
echo $t->working();      // Output: (null)
echo is_callable(array($t, 'testing'));       // Output: TRUE
echo is_callable(array($t, 'testingOther'));  // Output: TRUE
echo is_callable(array($t, 'working'));       // Output: TRUE, expected: FALSE

?>

三、实质区别:

method_exists检查类的方法是否存在,只要在类内部定义有此方法,就返回true

is_callable检测参数是否为合法的可调用结构 ,只有当外部可以访问到方法时,才返回true


猜你喜欢

转载自blog.csdn.net/qq_34206560/article/details/79558549