Callback functions in PHP are functions passed as arguments to other functions for flexible execution. They can be regular functions, anonymous functions, or class methods. Commonly used in array functions like array_map()
or sorting with usort()
. Callbacks allow dynamic and reusable logic. This guide covers syntax, examples, and use cases.
1. What is a Callback Function?
- It can be a simple string with the function name.
- Can be an anonymous function, or
- An array with object/class + method name.
2. Simple Callback Example
function sayHello($name) {
return "Hello, $name!";
}
function greetUser($callback, $name) {
echo $callback($name);
}
greetUser("sayHello", "John");
File to add: callback_example.php
or any function handling logic.
3. Using Anonymous Function as Callback
function processNumber($callback, $num) {
return $callback($num);
}
$result = processNumber(function($n) {
return $n * $n;
}, 5);
echo $result; // Output: 25
File to add: math_operations.php
or callback_example.php
4. Callback with array_map()
function square($n) {
return $n * $n;
}
$numbers = [1, 2, 3, 4];
$squares = array_map("square", $numbers);
print_r($squares);
Common in: Data transformation files like array_utils.php
5. Object-Oriented Callback
class MyMath {
public static function cube($n) {
return $n * $n * $n;
}
}
$nums = [1, 2, 3];
$result = array_map(["MyMath", "cube"], $nums);
print_r($result);
File: oop_callback.php
or any class utility file.
6. Callback with usort()
$people = [
["name" => "John", "age" => 22],
["name" => "Ravi", "age" => 28]
];
usort($people, function($a, $b) {
return $a['age'] <=> $b['age'];
});
print_r($people);
File: sort_people.php
or used in data sorting files.
Summary Table
Usage | Example Function | Used In Files |
---|---|---|
Simple callback | greetUser("func", x) |
callback_example.php |
Anonymous function | function($x){} |
math_operations.php |
Array function | array_map("func", x) |
array_utils.php |
Object/class method call | ["Class", "method"] |
oop_callback.php |
Sorting callback | usort($arr, fn) |
sort_people.php |