


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.
<?php if (method_exists($object, 'SomeMethod')) { $object->SomeMethod($this, TRUE); } ?>
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, 'SomeMethod'))) { $object->SomeMethod($this, TRUE); } ?>
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, 'PublicMethod'), array($foo, 'PrivateMethod'), array($foo, 'PublicStaticMethod'), array($foo, 'PrivateStaticMethod'), array('Foo', 'PublicMethod'), array('Foo', 'PrivateMethod'), array('Foo', 'PublicStaticMethod'), array('Foo', 'PrivateStaticMethod'), ); foreach ($callbacks as $callback){ var_dump($callback); var_dump(method_exists($callback[0], $callback[1])); var_dump(is_callable($callback)); echo str_repeat('-', 10); echo '<br />'; }
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 'Calling object method ' . $name . ' ' .implode(', ', $arguments); echo '<br />'; } }$obj = new MethodTest();$obj->runtest('in object context'); var_dump(method_exists($obj,'runtest')); var_dump(is_callable(array($obj,'runtest'))); echo '<br />';
Run results
Calling object method runtest in object context
bool(false) bool(true)
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, 'SomeMethod')) { $object->SomeMethod($this, TRUE); }?>
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, 'SomeMethod'))) { $object->SomeMethod($this, TRUE); } ?>
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, 'PublicMethod'), array($foo, 'PrivateMethod'), array($foo, 'PublicStaticMethod'), array($foo, 'PrivateStaticMethod'), array('Foo', 'PublicMethod'), array('Foo', 'PrivateMethod'), array('Foo', 'PublicStaticMethod'), array('Foo', 'PrivateStaticMethod'), ); foreach ($callbacks as $callback){ var_dump($callback); var_dump(method_exists($callback[0], $callback[1])); var_dump(is_callable($callback)); echo str_repeat('-', 10); echo '<br />'; }
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 'Calling object method ' . $name . ' ' .implode(', ', $arguments); echo '<br />'; } } $obj = new MethodTest();$obj->runtest('in object context'); var_dump(method_exists($obj,'runtest')); var_dump(is_callable(array($obj,'runtest'))); echo '<br />';
Running result
Calling object method runtest in object context
bool(false) bool(true)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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. 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 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.

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! 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:

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.

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
