Mastering PHP’s is_callable(): Safely Verify Functions and Methods
This article explains PHP’s is_callable() function, its parameters, and provides clear code examples showing how to verify both standalone functions and class methods before invoking them, helping developers write more robust and maintainable backend code.
In PHP, the is_callable() function checks whether a function or method can be called, returning true if it is callable and false otherwise, which is useful for dynamic calls.
The function accepts one or two arguments: with a single argument it checks that the given function or method name is callable; with two arguments the first is an array containing an object and method name to be checked.
Below are concrete code examples demonstrating the usage of is_callable().
Example 1: Using is_callable() to check if a function is callable
<?php
// Define a function
function add($a, $b) {
return $a + $b;
}
// Check if function is callable and output result
if (is_callable('add')) {
echo "函数add是可调用的";
} else {
echo "函数add不可调用";
}
?>This example defines a function add() and uses is_callable('add') to verify its callability, outputting a message accordingly.
Example 2: Using is_callable() to check if a method is callable
<?php
// Define a class
class Math {
public function multiply($a, $b) {
return $a * $b;
}
}
// Create an object
$math = new Math();
// Check if method is callable and output result
if (is_callable([$math, 'multiply'])) {
echo "方法multiply是可调用的";
} else {
echo "方法multiply不可调用";
}
?>This example defines a class Math with a method multiply(), creates an instance $math, and uses is_callable([$math, 'multiply']) to test the method’s callability.
The is_callable() function is a valuable tool in PHP for improving code robustness and maintainability by ensuring that functions or methods exist before invoking them.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
