1 min read

PHP Callback Functions

A callback function (often referred to as just "callback") is a function which is passed as an argument into another function.

Any existing function can be used as a callback function. To use a function as a callback function, pass a string containing the name of the function as the argument of another function.


1. Passing Function as a String

You can pass the name of a function as a string to another function.

function my_callback($item) {
  return strlen($item);
}

$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map("my_callback", $strings);
print_r($lengths);
// Outputs: Array ( [0] => 5 [1] => 6 [2] => 6 [3] => 7 )

2. Anonymous Functions as Callbacks

You can pass an anonymous function (closure) directly.

$strings = ["apple", "orange", "banana", "coconut"];
$lengths = array_map(function($item) { return strlen($item); }, $strings);

3. User-Defined Functions with Callbacks

You can define your own functions that accept callbacks. Use the callable type hint to ensure the argument is a function.

function process($str, callable $callback) {
    // Call the callback function
    echo $callback($str);
}

process("Hello World", function($str) {
    return strtoupper($str);
});
// Outputs: HELLO WORLD

4. call_user_func

The call_user_func() function is used to call the callback given by the first parameter.

function barber($type) {
    echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");

programming/php/php programming/php/php-anonymous-functions