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

This guide explains PHP's is_callable() function, shows how it returns true for callable functions or methods and false otherwise, provides a complete code example with expected output, and discusses broader uses such as checking class constructors and static methods for more robust code.

php Courses
php Courses
php Courses
How to Use PHP’s is_callable() to Safely Check Functions and Methods

In PHP, the is_callable() function lets you verify whether a variable can be invoked as a function or method, returning true if it is callable and false otherwise.

Basic Usage

The function accepts a single argument—the variable to test—and returns a boolean indicating its callability.

Example Code

<?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, testFunction() exists, so is_callable($functionName) returns true and prints "Yes". The variable $methodName refers to a non‑existent function, so is_callable($methodName) returns false and prints "No".

functionName is callable? Yes
methodName is callable? No

Extended Capabilities

Beyond simple functions and methods, is_callable() can also check whether a class constructor or a static method of a class is callable, making it useful for writing more defensive code.

Practical Advice

Before invoking a function or method, you can call is_callable() to ensure it exists, thereby avoiding runtime errors and improving code robustness.

Overall, is_callable() is a valuable PHP utility for determining the callability of variables, helping developers handle dynamic calls safely.

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.

code-exampleis_callablefunction check
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.