Analysis of the difference between method_exists() and is_callable() functions in php

WBOY
Release: 2016-07-25 08:58:26
Original
1795 people have browsed it
This article introduces the difference between method_exists() and is_callable() functions in PHP. Friends in need can refer to it.

Understand the difference between php function method_exists() and is_callable()? In the PHP object-oriented design process, it is often necessary 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 contrast, the is_callable() function is more advanced. It accepts the method name in the form of a string variable as the first parameter, and returns 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.

Having said so much, look at the following examples:

<?php
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 given method or function name is syntactically correct, not whether it actually exists. 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.

Example:

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

Instructions: The difference between php function method_exists() and is_callable(), in php5, the existence of a method does not mean that 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.

That’s all. I hope it helps everyone understand the difference between these two functions.



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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template