Using PHP’s is_callable() Function to Check Callability of Functions, Methods, and Constructors
This article explains how to use PHP's is_callable() function to determine whether a given function, method, class constructor, or static method can be invoked, demonstrates the syntax with a complete example, and shows the expected output for both callable and non‑callable identifiers.
In PHP, we often need to verify whether a function or method can be called. The is_callable() function provides a simple way to perform this check.
The is_callable() function accepts a single argument—the variable to be examined—and returns a boolean value: true if the variable is callable, otherwise false .
Below is a straightforward example demonstrating its usage:
<?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 we define a function named testFunction() . We then assign the function name and a non‑existent method name to the variables $functionName and $methodName respectively.
Using is_callable() , we check each variable. If the variable is callable, the script outputs "Yes"; otherwise it outputs "No".
Because testFunction() exists, $functionName is callable and is_callable($functionName) returns true . The method name stored in $methodName does not exist, so is_callable($methodName) returns false .
Running the code produces the following output:
functionName is callable? Yes
methodName is callable? NoThis example illustrates how is_callable() can be used to determine callability and the resulting behavior.
Beyond functions and methods, is_callable() can also verify whether class constructors and static class methods are callable.
By incorporating is_callable() checks before invoking functions or methods, developers can write more robust code and avoid runtime errors caused by attempting to call undefined callables.
Overall, is_callable() is a valuable PHP function that helps developers assess whether a variable can be invoked, enabling appropriate handling in their code.
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.