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 ) ) ) { /*要操作的代码段*/ }
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 ) ) { /*要操作的代码段*/ }
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!