PHP Callbacks/Callables

Callbacks are functions or methods that can be called dynamically using their names or references. In PHP, any callable entity (functions, methods, closures) can be passed as a parameter and executed later using built-in functions like call_user_func().

Checking if Something is Callable

The is_callable() function verifies if an identifier can be called as a function ?

<?php
var_dump(is_callable("abs"));
var_dump(is_callable("nonexistent_function"));
?>
bool(true)
bool(false)

Using Built-in Functions as Callbacks

Built-in PHP functions can be called using call_user_func() ?

<?php
echo call_user_func("strtoupper", "hello world") . "<br>";
echo call_user_func("abs", -5);
?>
HELLO WORLD
5

User-Defined Function Callbacks

Custom functions can also be called dynamically ?

<?php
function greet($name) {
    return "Hello, " . $name;
}

echo is_callable("greet") . "<br>";
echo call_user_func("greet", "Alice");
?>
1
Hello, Alice

Object Method Callbacks

Instance methods are passed as an array containing the object and method name ?

<?php
class Calculator {
    function add($a, $b) {
        return $a + $b;
    }
}

$calc = new Calculator();
echo call_user_func(array($calc, "add"), 5, 3) . "<br>";
echo call_user_func([$calc, "add"], 10, 2);
?>
8
12

Static Method Callbacks

Static methods can be called using the class name instead of an object instance ?

<?php
class MathUtils {
    static function multiply($a, $b) {
        return $a * $b;
    }
}

echo call_user_func(array("MathUtils", "multiply"), 4, 6) . "<br>";
echo call_user_func("MathUtils::multiply", 3, 7);
?>
24
21

Anonymous Functions as Callbacks

Closures and anonymous functions can also be used as callbacks ?

<?php
$square = function($n) {
    return $n * $n;
};

echo call_user_func($square, 5) . "<br>";

// Direct callback usage
$numbers = [1, 2, 3, 4];
$squared = array_map($square, $numbers);
print_r($squared);
?>
25
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
)

Conclusion

PHP callbacks provide flexibility for dynamic function calls. Use is_callable() to verify callables and call_user_func() to execute them. This enables powerful patterns like event handling and functional programming.

Updated on: 2026-03-15T09:18:27+05:30

931 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements