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():
<?php
// Example 1: Check if a function is callable
// Define a function
function add($a, $b) {
return $a + $b;
}
// Check if the function is callable and output the result
if (is_callable('add')) {
echo "Function add is callable";
} else {
echo "Function add is not callable";
}
// Example 2: Check if a class method is callable
// Define a class
class Math {
public function multiply($a, $b) {
return $a * $b;
}
}
// Create an object
$math = new Math();
// Check if the method is callable and output the result
if (is_callable([$math, 'multiply'])) {
echo "Method multiply is callable";
} else {
echo "Method multiply is not 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.
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.
