How to Use PHP’s is_callable() to Safely Check Functions and Methods
This guide explains how the PHP is_callable() function can determine whether a given variable, such as a function name or method name, is callable, demonstrates its usage with sample code, and shows how it helps write more robust backend code by preventing runtime errors.
In PHP development you often need to verify whether a function or method can be invoked; the built‑in is_callable() function provides a simple way to perform this check. is_callable() accepts a single argument—the variable to test—and returns a boolean: true if the variable is callable, otherwise false.
Example code:
<?php
function testFunction() {
echo "Hello, world!";
}
$functionName = 'testFunction';
$methodName = 'nonExistent';
echo "functionName is callable? ";
if (is_callable($functionName)) {
echo "Yes";
} else {
echo "No";
}
echo "<br>";
echo "methodName is callable? ";
if (is_callable($methodName)) {
echo "Yes";
} else {
echo "No";
}
?>In this script testFunction() is defined, then its name is stored in $functionName while a non‑existent method name is stored in $methodName.
The is_callable() calls test each variable: the existing function returns true and prints “Yes”, whereas the missing method returns false and prints “No”.
functionName is callable? Yes
methodName is callable? NoBeyond functions and methods, is_callable() can also verify class constructors and static methods, making it a versatile tool for runtime checks.
By checking callability before invoking a function or method, developers can avoid fatal errors and write more defensive, reliable backend code.
Overall, is_callable() is a valuable PHP function for determining whether a variable can be executed, helping to improve code safety and robustness.
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.
