Resolve the differences between the php function method_exists of and is_callable of

  • 2020-06-19 09:51:22
  • OfStack

What is the difference between the php function method_exists() and is_callable()? In php object-oriented design process, we often need to call a certain whether a method belongs to a class of judgment, the commonly used methods are method_exists () and is_callable (), by contrast, is_callable () function to some senior 1, it accepts the method name in the form of a string variable as the first parameter, if the presence of class methods and can call, it returns true. If you want to check that a method in a class can be called, you can pass the function an array instead of the class's method name as an argument. The array must contain the object or class name as its first element, and the method name to be checked as its second element. If the method exists in the class, the function returns true.
Code examples:

if ( is_callable( array( $obj, $method ) ) ) 
{ 
/* The snippet of code to operate on */
} 

is_callable() can take one more argument: a Boolean, and if set to true, the function simply checks for the syntax correctness of a given method or function name without checking for its actual existence. The method_exists() function takes 1 object (or class name) and 1 method name and returns true if the given method exists in the object's class
Code examples:

if ( method_exists( $obj, $method ) ) 
{ 
/* The snippet of code to operate on */
} 

The php function method_exists() differs from is_callable() in that in php5, just because a method exists doesn't mean it can be called. For methods of type private, protected, and public, method_exits() returns true, but is_callable() checks to see if it exists and returns false if it is of type private, protected.

Related articles: