Mastering PHP’s is_callable(): Safely Check Functions and Methods
This guide explains how PHP's is_callable() function works, its parameters, and provides clear code examples for verifying both standalone functions and class methods before invocation, helping developers write more robust and maintainable code.
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 you to verify existence before execution. is_callable() accepts one or two arguments: with a single argument it checks the given function or method name; with two arguments the first is an array containing an object (or class) and method name to verify.
Example 1: Using is_callable() to check a function
<?php
// Define a function
function add($a, $b) {
return $a + $b;
}
// Check if the function is callable and output the result
if (is_callable('add')) {
echo "Function add is callable";
} else {
echo "Function add is not callable";
}
?>In this example, we define a function add() and use is_callable('add') to determine if it can be called, printing a message based on the result.
Example 2: Using is_callable() to check a method
<?php
// Define a class
class Math {
public function multiply($a, $b) {
return $a * $b;
}
}
// Create an object
$math = new Math();
// Check if the method is callable and output the result
if (is_callable([$math, 'multiply'])) {
echo "Method multiply is callable";
} else {
echo "Method multiply is not callable";
}
?>Here we define a Math class with a multiply() method, instantiate it, and use is_callable([$math, 'multiply']) to verify the method's callability, outputting the appropriate message.
The is_callable() function is a valuable tool in PHP for enhancing code robustness and maintainability by ensuring that functions or methods exist before attempting to invoke them.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
