A callback function in PHP is a function that is passed as an argument to another function, allowing the receiving function to execute (call) the passed function at a later time or under specific conditions. This provides dynamic behavior and flexibility, making code more reusable and modular.
function greet($name) {
return "Hello, " . $name . "!";
}
function processUser($callback) {
$name = "User";
echo $callback($name);
}
processUser('greet'); // Output: Hello, User!
$numbers = [1, 2, 3, 4];
$double = array_map(function($n){
return $n * 2; }, $numbers);
print_r($double);
// Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
class Greeter {
public function greet($name) {
echo "Hello, " . $name . "!";
}
}
function processUserMethod($callback) {
$name = "Alice";
call_user_func($callback, $name);
}
$greeter = new Greeter();
processUserMethod([$greeter, 'greet']);
// Outputs: Hello, Alice!
PHP has many built-in functions that accept callbacks, such as:
Let's see the example of call_user_func().
function sayHello($name) {
return "Hello, " . $name . "!";
}
echo call_user_func('sayHello', 'World'); // Output: Hello, World!
Callback functions are a core concept for writing efficient and modular PHP code, making functions highly customizable and dynamic.