Using PHP's is_callable() to Check Callable Functions and Methods
This article explains PHP's is_callable() function, describing its purpose, parameter options, and how to use it to verify the callability of functions and class methods, accompanied by clear code examples and a discussion of its benefits for robust, maintainable code.
In PHP, the is_callable() function checks whether a function or method can be called. It returns a boolean true if callable, otherwise false, making it useful for dynamic calls by verifying existence before invocation.
The function accepts either one or two arguments. With a single argument it checks the callable status of that function or method name; with two arguments, the first must be an array containing an object and method name, which it then checks.
Below are concrete code examples demonstrating the usage of is_callable() .
Example 1: Using is_callable() to check if a function is callable
<code><?php
// 定义一个函数
function add($a, $b) {
return $a + $b;
}
// 检查函数是否可调用,并输出结果
if (is_callable('add')) {
echo "函数add是可调用的";
} else {
echo "函数add不可调用";
}
?></code>In this example we first define a function add() . Then we call is_callable('add') to verify that add is callable and output the corresponding message.
Example 2: Using is_callable() to check if a method is callable
<code><?php
// 定义一个类
class Math {
public function multiply($a, $b) {
return $a * $b;
}
}
// 创建一个对象
$math = new Math();
// 检查方法是否可调用,并输出结果
if (is_callable([$math, 'multiply'])) {
echo "方法multiply是可调用的";
} else {
echo "方法multiply不可调用";
}
?></code>Here we define a class Math with a method multiply() , create an instance $math , and use is_callable([$math, 'multiply']) to test the method's callability, printing the result.
The is_callable() function is a valuable tool in PHP for pre‑checking functions or methods before invoking them, greatly improving code robustness and maintainability by preventing errors from calling undefined callables.
PHP learning recommendations:
Vue3+Laravel8+Uniapp beginner to practical development tutorial
Vue3+TP6+API social e‑commerce system development tutorial
Swoole from beginner to mastery recommended course
Workerman+TP6 instant messaging chat system limited‑time offer
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.