Backend Development 4 min read

Using PHP’s is_callable() Function to Check Callable Functions and Methods

This article explains PHP’s is_callable() function, detailing its purpose, parameter options, and how to use it to verify whether functions or class methods are callable, accompanied by clear code examples demonstrating checks on a simple function and a class method.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP’s is_callable() Function to Check Callable Functions and Methods

In PHP, the is_callable() function is used to determine whether a function or method can be called, returning true if it is callable and false otherwise, which is useful for dynamic calls.

The function accepts either one or two arguments: with a single argument it checks the callable status of the given function or method name, while with two arguments it treats the first as an array containing an object and method name to verify.

The following code examples illustrate how to use is_callable() for both a standalone function and a class method.

<?php
// Example 1: Check if a function is callable

// Define a function
function add($a, $b) {
    return $a + $b;
}

// Check the function and output the result
if (is_callable('add')) {
    echo "函数add是可调用的";
} else {
    echo "函数add不可调用";
}

// Example 2: Check if a method is callable

// Define a class
class Math {
    public function multiply($a, $b) {
        return $a * $b;
    }
}

// Create an object
$math = new Math();

// Check the method and output the result
if (is_callable([$math, 'multiply'])) {
    echo "方法multiply是可调用的";
} else {
    echo "方法multiply不可调用";
}
?>

In Example 1, a function named add() is defined and is_callable('add') is used to verify its callability, printing a message based on the result.

In Example 2, a class Math with a method multiply() is defined; an instance $math is created, and is_callable([$math, 'multiply']) checks whether the multiply method can be called, outputting the corresponding message.

In summary, the is_callable() function is a valuable tool in PHP for pre‑checking the callability of functions or methods, enhancing code robustness and maintainability by preventing errors from invoking undefined callables.

BackendPHPCode ExampleTutorialCallablefunctionis_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.