Home Backend Development PHP Tutorial Explore the is_callable() and method_exists() functions in PHP

Explore the is_callable() and method_exists() functions in PHP

Sep 06, 2017 pm 04:24 PM
callable exists method

In many product applications, we can often see the following usage, which is used to check whether a method in an object exists.

<?php
    if (method_exists($object, &#39;SomeMethod&#39;)) {   
    $object->SomeMethod($this, TRUE); 
    }
?>
Copy after login

The purpose of this code is relatively easy to understand. There is an object called $object. We want to know whether it has a method called SomeMethod. If so, call this method.

This code looks correct and will run fine most of the time. But if the method of this $object object is invisible to the current running environment, can the program still run normally? Just as this function name method exists, it just checks whether the class or object we provide has the method we expect. If so, it returns TRUE. If not, it returns FALSE. The issue of visibility is not considered here. Therefore, when you happen to determine a private or protected method, you can get a correct return, but when executing, you will get a "Fatal Error" error warning.

The real intention of the above code should be understood as: for the provided class or object, can we call its SomeMethod method in the current scope. And this is the purpose of the is_callable() function. is_callable()The function receives a callback parameter, which can specify a function name or an array containing method names and objects. If it can be executed in the current scope, it returns TRUE.

<?php
    if (is_callable(array($object, &#39;SomeMethod&#39;))) {      
        $object->SomeMethod($this, TRUE); 
    }
?>
Copy after login

Let’s give an example to illustrate the difference between the two

<?phpclass Foo {
    public function PublicMethod(){}    
    private function PrivateMethod(){}    
    public static function PublicStaticMethod(){}    
    private static function PrivateStaticMethod(){}
}
    $foo = new Foo();$callbacks = array(    
    array($foo, &#39;PublicMethod&#39;),    
    array($foo, &#39;PrivateMethod&#39;),    
    array($foo, &#39;PublicStaticMethod&#39;),    
    array($foo, &#39;PrivateStaticMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PublicMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PrivateMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PublicStaticMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PrivateStaticMethod&#39;),
   );
   foreach ($callbacks as $callback){
    var_dump($callback);
    var_dump(method_exists($callback[0], $callback[1]));
    var_dump(is_callable($callback));    
    echo str_repeat(&#39;-&#39;, 10);    
    echo &#39;<br />&#39;;
}
Copy after login

After executing the above script, we will clearly see the difference between the two functions.

is_callable()There are other uses, for example, not checking the provided class or method, but only checking whether the syntax of the function or method is correct. Like method_exists(), is_callable() can trigger automatic loading of classes.

If an object has a magic method __call, method_exists() will return FALSE when judging the method, and is_callable() will return TRUE.

<?phpclass MethodTest {
    public function __call($name, $arguments){
      echo &#39;Calling object method &#39; . $name . &#39; &#39; .implode(&#39;, &#39;, $arguments);      
      echo &#39;<br />&#39;;
    }
}$obj = new MethodTest();$obj->runtest(&#39;in object context&#39;);
var_dump(method_exists($obj,&#39;runtest&#39;));
var_dump(is_callable(array($obj,&#39;runtest&#39;)));

echo &#39;<br />&#39;;
Copy after login

Run results

Calling object method runtest in object context
bool(false) bool(true)

Explore the is_callable() and method_exists() functions in PHP

In many product applications, we can often see the following usage, which is used to check whether a method in an object exists.

<?phpif (method_exists($object, &#39;SomeMethod&#39;)) {   
    $object->SomeMethod($this, TRUE); 
}?>
Copy after login

The purpose of this code is relatively easy to understand. There is an object called $object. We want to know whether it has a method called SomeMethod. If so, call this method.

This code looks correct and will run fine most of the time. But if the method of this $object object is invisible to the current running environment, can the program still run normally? Just as this function name method exists, it just checks whether the class or object we provide has the method we expect. If so, it returns TRUE. If not, it returns FALSE. The issue of visibility is not considered here. Therefore, when you happen to determine a private or protected method, you can get a correct return, but when executing, you will get a "Fatal Error" error warning.

The real intention of the above code should be understood as: for the provided class or object, can we call its SomeMethod method in the current scope. And this is the purpose of the is_callable() function. is_callable()The function receives a callback parameter, which can specify a function name or an array containing method names and objects. If it can be executed in the current scope, it returns TRUE.

<?php
    if (is_callable(array($object, &#39;SomeMethod&#39;))) {      
    $object->SomeMethod($this, TRUE); 
    }
?>
Copy after login

Let’s give an example to illustrate the difference between the two

<?php
    class Foo {
    public function PublicMethod(){}    
    private function PrivateMethod(){}    
    public static function PublicStaticMethod(){}    
    private static function PrivateStaticMethod(){}
}
$foo = new Foo();$callbacks = array(    
    array($foo, &#39;PublicMethod&#39;),    
    array($foo, &#39;PrivateMethod&#39;),    
    array($foo, &#39;PublicStaticMethod&#39;),    
    array($foo, &#39;PrivateStaticMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PublicMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PrivateMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PublicStaticMethod&#39;),    
    array(&#39;Foo&#39;, &#39;PrivateStaticMethod&#39;),
   );
   foreach ($callbacks as $callback){
    var_dump($callback);
    var_dump(method_exists($callback[0], $callback[1]));
    var_dump(is_callable($callback));    
    echo str_repeat(&#39;-&#39;, 10);    
    echo &#39;<br />&#39;;
}
Copy after login

After executing the above script, we will clearly see the difference between the two functions.

is_callable()There are other uses, for example, not checking the provided class or method, but only checking whether the syntax of the function or method is correct. Like method_exists(), is_callable() can trigger automatic loading of classes.

If an object has a magic method __call, method_exists() will return FALSE when judging the method, and is_callable() will return TRUE.

<?phpclass MethodTest {
    public function __call($name, $arguments){
      echo &#39;Calling object method &#39; . $name . &#39; &#39; .implode(&#39;, &#39;, $arguments);      
      echo &#39;<br />&#39;;
    }
}
$obj = new MethodTest();$obj->runtest(&#39;in object context&#39;);
var_dump(method_exists($obj,&#39;runtest&#39;));
var_dump(is_callable(array($obj,&#39;runtest&#39;)));
echo &#39;<br />&#39;;
Copy after login

Running result

Calling object method runtest in object context
bool(false) bool(true)

Explore the is_callable() and method_exists() functions in PHP

The above is the detailed content of Explore the is_callable() and method_exists() functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to PHP Fatal error: Call to a member function fetch() Solution to PHP Fatal error: Call to a member function fetch() Jun 23, 2023 am 09:36 AM

When using PHP for web application development, you will often need to use a database. When using a database, error messages are very common. Among them, PHPFatalerror: Calltoamemberfunctionfetch() is a relatively common error that occurs when using PDO to query the database. So, what causes this error and how to solve it? This article will explain it in detail for you. 1. Cause of error

The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface Apr 21, 2023 am 08:04 AM

1. Basic features 1. It starts with an optimistic lock, and if lock conflicts are frequent, it is converted to a pessimistic lock. 2. It starts with a lightweight lock implementation, and if the lock is held for a long time, it is converted to a heavyweight lock. 3. The spin lock strategy that is most likely used when implementing lightweight locks 4. It is an unfair lock 5. It is a reentrant lock 6. It is not a read-write lock 2. The JVM will synchronize the locking process Locks are divided into no lock, biased lock, lightweight lock, and heavyweight lock states. It will be upgraded sequentially according to the situation. Biased lock assumes that the male protagonist is a lock and the female protagonist is a thread. If only this thread uses this lock, then the male protagonist and the female protagonist can live happily forever even if they do not get a marriage certificate (avoiding high-cost operations). But the female supporting role appears

How to use the File.Exists function in C# to determine whether a file exists How to use the File.Exists function in C# to determine whether a file exists Nov 18, 2023 am 11:25 AM

How to use the File.Exists function in C# to determine whether a file exists. In C# file operations, determining whether a file exists is a basic functional requirement. The File.Exists function is a method in C# used to determine whether a file exists. This article will introduce how to use the File.Exists function in C# to determine whether a file exists and provide specific code examples. Reference the namespace Before you start writing code, you first need to reference the System.IO namespace, which

How to use POST request method in jQuery How to use POST request method in jQuery Feb 28, 2024 pm 09:03 PM

How to use the POST request method in jQuery In web development, data interaction between the front-end page and the back-end server is often involved. Among them, POST request is a commonly used method. Through POST request, you can submit data to the backend server and obtain the corresponding return result. jQuery is a popular JavaScript library that provides a convenient way to make AJAX requests. This article will introduce how to use the POST method in jQuery for data transmission and provide specific instructions.

How to implement the Callable interface to create a thread class in java How to implement the Callable interface to create a thread class in java May 11, 2023 am 11:58 AM

Implementing the Callable interface to create a thread class has provided the Callable interface since Java 5. This interface is an enhanced version of the Runnable interface. The Callable interface provides a call() method as the thread execution body. The call() method can have a return value. The call() method Exceptions can be declared. booleancancel(booleanmay) attempts to cancel the Callable task associated with the Future. Vget() returns the return value of the call() method in the Call task. Calling this method will cause the thread to block, and you must wait for the child thread to end before getting the return value. Vget(longtimeout,Ti

PHP error: use null as callable solution! PHP error: use null as callable solution! Aug 19, 2023 pm 05:01 PM

PHP error: use null as callable solution! During the PHP development process, you often encounter some error messages. One of the common errors is "using null as callable". This error message indicates that when calling a callable object, a null value was passed as a parameter, resulting in the corresponding operation being unable to be performed. This error usually occurs when calling a callback function, method or instance of a class, and we need to pass the callable object as a parameter correctly. Here are some common code examples:

Using EXISTS function in MYSQL Using EXISTS function in MYSQL Feb 24, 2024 pm 05:15 PM

Usage of EXISTS in MYSQL, with code examples. In the MYSQL database, EXISTS is a very useful operator, used to determine whether a subquery returns at least one row of data. It is usually used with a WHERE clause to filter out data that meets conditions based on the results of a subquery. When using EXISTS, you need to pay attention to the following points: The EXISTS condition does not care about the specific data returned by the subquery, only whether there is data returned. The EXISTS condition can be used in combination with other conditions.

How to use java's Callable interface How to use java's Callable interface Apr 19, 2023 am 09:58 AM

Note 1. The Callable interface can return results or throw exception tasks, and the implementer can define a parameterless call method. 2. Different from the run method of Thread and Runnable, the execution method of Callable task is call. call() can return a value, but the run() method cannot. call() can throw checked exceptions, such as ClassNotFoundException, but run() cannot throw checked exceptions. Instance classMyCallableimplementsCallable{MyCallable(){}@OverridepublicInteger

See all articles