Using PHP's is_callable() Function to Verify Callability of Functions and Methods
This article explains PHP's is_callable() function, shows how it checks whether functions or methods are callable with one or two arguments, and provides clear code examples demonstrating its use with a simple function and a class method to improve code robustness.
In PHP, the is_callable() function is used to determine whether a given function or method can be called, returning true if it is callable and false otherwise, which is especially useful for dynamic calls.
The function accepts either a single argument—checking the callability of a function or method name—or two arguments, where the first is an array containing an object (or class name) and a method name, allowing verification of object methods.
Below are concrete code examples illustrating the usage of is_callable() :
In Example 1, a function add() is defined and then checked with is_callable('add') ; the script prints a message indicating whether the function is callable.
In Example 2, a class Math with a method multiply() is defined, an instance $math is created, and is_callable([$math, 'multiply']) verifies the method's callability, outputting the appropriate message.
Overall, is_callable() is a valuable PHP utility that helps developers verify the existence and callability of functions or methods before invoking them, thereby enhancing code robustness and maintainability.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.