Home > php教程 > PHP开发 > Analyze the difference between php function method_exists() and is_callable()

Analyze the difference between php function method_exists() and is_callable()

高洛峰
Release: 2016-12-22 15:42:24
Original
1120 people have browsed it

What is the difference between php function method_exists() and is_callable()? In the PHP object-oriented design process, we often need to make a judgment when calling a method whether it belongs to a certain class. Commonly used methods include method_exists() and is_callable(). In comparison, the is_callable() function is more advanced. Some, which accept the method name in the form of a string variable as the first argument, return true if the class method exists and can be called. If you want to check whether a method in a class can be called, you can pass an array to the function as a parameter instead of the method name of the class. The array must contain the object or class name as its first element and the method name to be checked as the second element. If the method exists in the class, the function returns true.
Code example:

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

is_callable() can add another parameter: a Boolean value. If this parameter is set to true, the function only checks whether the syntax of the given method or function name is correct, without checking whether it is true. exist. The parameters of the method_exists() function are an object (or class name) and a method name. If the given method exists in the object's class, it returns true
Code example:

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

PHP function method_exists() and is_callable() The difference is that in PHP5, just because a method exists doesn't mean it can be called. For methods of private, protected and public types, method_exits() will return true, but is_callable() will check whether it exists and can be accessed. If it is of private, protected type, it will return false.


For more articles on the difference between PHP functions method_exists() and is_callable(), please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template