Mastering PHP’s is_callable(): How to Safely Check Functions and Methods

This article explains PHP’s is_callable() function, detailing its purpose, parameter options, and practical usage through clear code examples that demonstrate checking both standalone functions and class methods before invocation to improve code robustness.

php Courses
php Courses
php Courses
Mastering PHP’s is_callable(): How to Safely Check 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. This is useful for dynamic calls, allowing verification before invocation.

The function accepts one or two arguments. With a single argument it checks if the given function or method name is callable; with two arguments the first is an array containing an object (or class) and a method name, which it then checks.

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 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 we define a function add() and use is_callable('add') to verify its callability, outputting a corresponding message.

In Example 2 we define a class Math with a method multiply(), create an instance $math, and use is_callable([$math, 'multiply']) to check if the method can be called, again printing the result.

In summary, is_callable() is a valuable PHP function that helps ensure functions or methods exist before calling them, enhancing code robustness and maintainability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPfunctionmethodis_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

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.