How to Safely Check Callability in PHP with is_callable()
This guide explains how PHP's is_callable() function can be used to determine whether a given function, method, class constructor, or static method is callable, provides a clear code example, shows the expected output, and highlights its role in writing more robust backend code.
In PHP you can determine whether a function or method can be invoked by using the built-in is_callable() function. is_callable() accepts a single argument – the variable to test – and returns true if it is callable, otherwise false.
Example:
<?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";
}
?>The script defines testFunction(), assigns its name to $functionName, and assigns a non‑existent name to $methodName. is_callable($functionName) returns true because the function exists, while is_callable($methodName) returns false.
functionName is callable? Yes
methodName is callable? NoBeyond simple functions, is_callable() can also verify class constructors and static methods, making it useful for writing more robust code that checks callability before invoking a routine.
Overall, is_callable() is a handy PHP utility for preventing runtime errors by confirming that a variable represents an executable function or method.
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.
