Understanding PHP Callback Functions
PHP is a popular server-side scripting language that has been around for decades. One of its useful features is the ability to use callback functions. In this
A callback (or "callable") is a function that you pass to another function so it can be called later. Callbacks are the foundation of PHP's higher-order functions — array_map, usort, array_filter, and many framework hooks all expect you to hand them a callback. This chapter explains what counts as a callable in PHP, the four ways to write one, and how to use them in everyday code.
This page assumes you already understand basic PHP functions. If you are new to defining functions, read that first.
What are PHP Callback Functions?
A PHP callback function is any function that is passed as an argument to another function, then invoked from inside it. PHP recognizes a value as callable in four forms:
- A function name string —
'strtoupper'refers to the built-instrtoupper()function. - An anonymous function (closure) —
function () { ... }assigned to a variable or passed inline. - An arrow function —
fn() => ..., a shorthand for short closures (PHP 7.4+). - An object/method reference —
[$object, 'methodName']or['ClassName', 'staticMethod'].
The type hint for a parameter that accepts any of these is callable. You can invoke the value directly ($callback()) or with call_user_func() / call_user_func_array() when you need to forward a dynamic list of arguments.
Why Use PHP Callback Functions?
Callbacks let you write a function once and customize its behaviour at the call site, without rewriting it:
- Reusability. A generic function (e.g. "loop over this list and do something to each item") works for any task you supply as a callback.
- Cleaner logic. Built-in higher-order functions like
array_mapandarray_filterreplace manual loops with a single, declarative line. - Decoupling. Event-driven code — form handlers, CLI command processors, framework hooks — registers a callback that runs only when the event fires, keeping the trigger and the handler separate.
How to Use PHP Callback Functions
Using PHP callback functions is straightforward. You simply pass the name of the function or the anonymous function as an argument to the parent function. Here is an example of how to use a named function as a callback:
PHP example of how to use a named function as a callback
In the example above, the myCallbackFunction is passed as an argument to the parentFunction. When the parentFunction is executed, it calls call_user_func and passes the myCallbackFunction as an argument. As a result, the myCallbackFunction is executed and outputs the message "The callback function has been executed."
Here is an example of how to use an anonymous function as a callback:
PHP example of how to use an anonymous function as a callback
In this example, the anonymous function is assigned to the variable $myCallbackFunction. This variable can then be passed as an argument to the parentFunction, just like the named function in the previous example.
Starting with PHP 7.4, you can also use the concise arrow function syntax (fn) for simple callbacks. Arrow functions automatically capture variables from the parent scope and provide a cleaner syntax for short callbacks:
$myCallback = fn() => print("The arrow callback function has been executed.");
parentFunction($myCallback);Passing Arguments to a Callback
Most useful callbacks receive data. The parent function decides which arguments to pass when it invokes the callback. Use call_user_func() to pass them positionally, or call_user_func_array() to forward an array of arguments:
<?php
function applyToPair(callable $callback, int $a, int $b) {
return call_user_func($callback, $a, $b);
}
$add = fn(int $x, int $y) => $x + $y;
$multiply = fn(int $x, int $y) => $x * $y;
echo applyToPair($add, 4, 6); // 10
echo "\n";
echo applyToPair($multiply, 4, 6); // 24Here applyToPair does not know whether it is adding or multiplying — that decision lives in the callback you pass.
Using Callbacks with Built-in Functions
The most common place you will use callbacks is PHP's array functions. They take a callback and apply it across a list, replacing hand-written loops.
<?php
$numbers = [1, 2, 3, 4, 5];
// array_map: transform every element
$squares = array_map(fn($n) => $n * $n, $numbers);
echo implode(', ', $squares); // 1, 4, 9, 16, 25
echo "\n";
// array_filter: keep elements where the callback returns true
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
echo implode(', ', $evens); // 2, 4
echo "\n";
// usort: sort using a comparison callback (descending order)
$values = [3, 1, 4, 1, 5];
usort($values, fn($a, $b) => $b <=> $a);
echo implode(', ', $values); // 5, 4, 3, 1, 1For more on sorting, see Sorting Arrays in PHP.
Using Object Methods as Callbacks
A callback can also point at a method. Pass [$object, 'methodName'] for an instance method, or ['ClassName', 'staticMethod'] for a static one:
<?php
class Greeter {
public function greet(string $name): string {
return "Hello, {$name}!";
}
public static function shout(string $name): string {
return strtoupper("Hi {$name}");
}
}
$greeter = new Greeter();
// Instance method as a callback
echo call_user_func([$greeter, 'greet'], 'Ada'); // Hello, Ada!
echo "\n";
// Static method as a callback
echo call_user_func(['Greeter', 'shout'], 'Ada'); // HI ADATip: Since PHP 8.1 you can use the first-class callable syntax —
$greeter->greet(...)orstrtoupper(...)— to get aClosurefrom any callable without quoting strings, which is safer and IDE-friendly.
Conclusion
In conclusion, PHP callback functions are a powerful tool for PHP programming. They allow for code reusability, simplify complex code, and enable server-side event-driven programming. By understanding how to use PHP callback functions, you can take your PHP skills to the next level.