How to Use PHP’s is_callable() to Safely Check Functions and Methods
This article explains PHP’s is_callable() function, showing how it determines whether a given variable, function, method, constructor, or static method can be called, with clear code examples and output demonstrating true for existing functions and false for non‑existent methods.
In PHP, you can determine whether a function or method can be called by using the is_callable() function.
The is_callable() function takes a single argument—the variable to check—and returns a boolean: true if the variable is callable, otherwise false.
Below is a simple 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 a function testFunction() and assigns its name and a non‑existent method name to $functionName and $methodName respectively. It then uses is_callable() to test each variable, outputting “Yes” for the existing function and “No” for the missing method.
functionName is callable? Yes
methodName is callable? NoThis demonstrates that is_callable() can verify functions, methods, class constructors, and static methods before invoking them, helping you write more robust PHP code.
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.
