Backend Development 3 min read

Using PHP is_callable() to Verify Callable Functions and Methods

This article explains PHP's is_callable() function, its single‑ and two‑argument usage, and demonstrates with code examples how to check whether a function like add() or a class method such as Math::multiply() is callable before invoking it.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP is_callable() to Verify Callable Functions and Methods

The is_callable() function in PHP checks whether a given function or method can be called, returning true if it is callable and false otherwise, which is useful for dynamic calls.

It accepts either one argument (a function name or a callable string) or two arguments, where the first argument is an array containing an object (or class name) and a method name, allowing the function to verify method callability.

Below are concrete code examples illustrating 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 class 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, the function add() is defined and is_callable('add') is used to verify its callability, outputting a corresponding message.

In Example 2, a Math class with a multiply() method is defined, an instance $math is created, and is_callable([$math, 'multiply']) checks whether the method can be invoked, again printing the result.

In summary, is_callable() is a valuable PHP utility that helps improve code robustness and maintainability by ensuring functions or methods exist before they are called, preventing runtime errors.

BackendPHPTutorialCallablefunctionis_callable
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.