Home  >  Article  >  Backend Development  >  php中method_exists()与is_callable()的区别

php中method_exists()与is_callable()的区别

WBOY
WBOYOriginal
2016-06-20 13:00:33899browse

php中method_exists()与is_callable()的区别

本篇文章是对php中method_exists()与is_callable()的区别进行了详细的分析介绍,需要的朋友参考下 php函数method_exists() 与is_callable()的区别在哪?在php面相对象设计过程中,往往我们需要在调用某一个方法是否属于某一个类的时候做出判断,常用的方法有 method_exists()和is_callable(),相比之下,is_callable()函数要高级一些,它接受字符串变量形式的方法名作为 第一个参数,如果类方法存在并且可以调用,则返回true。如果要检测类中的方法是否能被调用,可以给函数传递一个数组而不是类的方法名作为参数。数组必须包含对象或类名,以将其作为它的第一个元素,要检查的方法名则作为第二个元素。如果该方法在类中存在,函数返回true。
代码示例:

if ( is_callable( array( $obj, $method ) ) )
{
/*要操作的代码段*/
}


is_callable()可以加收另外一个参数:一个布尔值,如果将该参数设置为true,函数仅仅检查给定的方法或函数名称的语法是否正确,而不检查其是否真正存在。method_exists()函数的参数为一个对象(或类名)和一个方法名,如果给定方法在对象的类中存在,则返回true
代码示例:

if ( method_exists( $obj, $method ) )
{
/*要操作的代码段*/
}


php函数method_exists()与is_callable()的区别在于在php5中,一个方法存在并不意味着它就可以被调用。对于 private,protected和public类型的方法,method_exits()会返回true,但是is_callable()会检查存在其是否可以访问,如果是private,protected类型的,它会返回false。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn