Backend Development 4 min read

Using is_callable() in PHP to Check Callable Functions and Methods

This article explains PHP's is_callable() function, its parameters, and demonstrates its use with code examples for checking the callability of both functions and class methods, highlighting how it improves code robustness and maintainability.

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

In PHP, the is_callable() function checks 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 argument (the function or method name) or two arguments (an array containing an object and method name) to perform the check.

The following code examples demonstrate how to use is_callable() in practice.

<?php
// 示例1:使用is_callable()检查函数是否可调用

// 定义一个函数
function add($a, $b) {
    return $a + $b;
}

// 检查函数是否可调用,并输出结果
if (is_callable('add')) {
    echo "函数add是可调用的";
} else {
    echo "函数add不可调用";
}

// 示例2:使用is_callable()检查方法是否可调用

// 定义一个类
class Math {
    public function multiply($a, $b) {
        return $a * $b;
    }
}

// 创建一个对象
$math = new Math();

// 检查方法是否可调用,并输出结果
if (is_callable([$math, 'multiply'])) {
    echo "方法multiply是可调用的";
} else {
    echo "方法multiply不可调用";
}
?>

In Example 1, a function add() is defined and is_callable('add') is used to verify its callability, outputting 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 method can be called, again printing a corresponding message.

In summary, is_callable() is a valuable PHP function that helps ensure code robustness and maintainability by verifying callability before invoking functions or methods.

PHP实战开发极速入门

扫描二维码免费领取学习资料

backend developmentphpcode examplesis_callablecallable functions
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.