A Callback Function (or simply a “callback”) is a function that is passed as an argument to another function and is intended to be executed at a later time by that receiving function.
This allows you to customize the behavior of generic functions without needing to modify their core code. It’s the core principle behind array sorting, event handling, and asynchronous operations.
1. Defining a Callback
In PHP, a callback can be defined in three primary ways:
| Type | How to Define | Example |
| Named Function | A simple string containing the function’s name. | 'my_custom_filter' |
| Anonymous Function (Closure) | A function defined on the fly without a name. | function($item) { ... } |
| Object Method | An array containing the object and the method name. | [$obj, 'method_name'] |
2. The call_user_func() and call_user_func_array()
These two utility functions are the simplest way to demonstrate how callbacks work. They execute the function passed as the first argument.
call_user_func(callback, arg1, arg2, ...): Executes a function with arguments passed individually.call_user_func_array(callback, array_of_args): Executes a function with arguments passed as an array.
Example: Using a Named Function Callback
<?php
// The function we want to "call back"
function greet_user($name, $greeting = "Hello") {
return "$greeting, $name!";
}
// Call the function indirectly using its name (a string)
$result = call_user_func('greet_user', 'Alice', 'Good Morning');
echo $result; // Output: Good Morning, Alice!
?>
3. Practical Use Case: Custom Array Filtering
The most common practical use of callbacks is with PHP’s built-in array functions, such as array_filter(), array_map(), and usort() (User-defined sort).
array_filter()
This function iterates over an array and keeps only the elements for which the callback function returns a truthy value.
Example: Filtering for Even Numbers
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
// Define an Anonymous Function (Closure) as the callback
$even_checker = function($number) {
return ($number % 2 == 0); // Returns true if number is even
};
// array_filter passes each $number to $even_checker()
$even_numbers = array_filter($numbers, $even_checker);
echo "Original: " . implode(', ', $numbers) . "<br>";
echo "Filtered: " . implode(', ', $even_numbers);
// Output: Filtered: 2, 4, 6, 8
?>
array_map()
This function executes the callback on every element of an array and returns a new array containing the results.
Example: Doubling Every Number
<?php
$values = [10, 20, 30];
// Callback to double the value
$doubler = function($n) {
return $n * 2;
};
$doubled_values = array_map($doubler, $values);
echo "Doubled: " . implode(', ', $doubled_values); // Output: Doubled: 20, 40, 60
?>
4. Closures and the use Keyword (Accessing External Variables)
An Anonymous Function (or Closure) has special access rules. By default, it cannot access variables defined in the scope where it was created. To access those external variables, you must explicitly pass them using the use keyword.
Example: Filtering Based on a Dynamic Threshold
<?php
$products = [50, 120, 80, 200];
$tax_rate = 0.20; // External variable
// We must 'use' $tax_rate to access it inside the anonymous function
$tax_calculator = function($price) use ($tax_rate) {
return $price * (1 + $tax_rate);
};
$prices_with_tax = array_map($tax_calculator, $products);
echo "Prices with tax: " . implode(', ', $prices_with_tax);
// Output: Prices with tax: 60, 144, 96, 240 (50*1.20=60, etc.)
?>
5. Type Hinting Callables
For clarity and error checking, you can use the callable type hint in function definitions to ensure the argument passed is a valid function, object method, or anonymous function.
<?php
function execute_logic(callable $func, $data) {
// We are guaranteed that $func is something we can execute
return $func($data);
}
?>
