How to Safely Use PHP’s is_callable() to Verify Functions and Methods
This article explains how PHP's is_callable() function determines whether a function or method can be invoked, describes its one‑ and two‑argument signatures, and provides clear code examples for checking both standalone functions and class methods, helping developers write more robust 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. This is useful for dynamic calls to ensure the target exists before invoking it.
The function accepts one or two arguments. With a single argument it checks if the given function or method name is callable. With two arguments, the first is an array containing an object (or class name) and a method name, and it checks whether that method is callable.
Below are concrete code examples demonstrating the usage of is_callable():
<?php
// Example 1: check if a function is callable
function add($a, $b) {
return $a + $b;
}
if (is_callable('add')) {
echo "Function add is callable";
} else {
echo "Function add is not callable";
}
// Example 2: check if a method is callable
class Math {
public function multiply($a, $b) {
return $a * $b;
}
}
$math = new Math();
if (is_callable([$math, 'multiply'])) {
echo "Method multiply is callable";
} else {
echo "Method multiply is not callable";
}
?>In Example 1 we define a function add() and use is_callable('add') to verify its callability, outputting a corresponding message.
In Example 2 we define a class Math with a method multiply(), create an instance $math, and use is_callable([$math, 'multiply']) to check if the method can be called, again printing the result.
In summary, is_callable() is a valuable PHP function that helps improve code robustness and maintainability by allowing developers to verify the existence of functions or methods 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.
