PHP Callback Functions
Callback functions in PHP are functions that are passed as arguments to other functions. They are often used to customize the behavior of functions and can be defined as anonymous functions or as named functions.
Using Callback Functions
<?php
function my_callback($value) {
return $value * 2;
}
function process_array($array, $callback) {
$result = [];
foreach ($array as $value) {
$result[] = $callback($value);
}
return $result;
}
$array = [1, 2, 3, 4];
$result = process_array($array, 'my_callback');
print_r($result);
?>
Explanation: In this example, the my_callback
function is defined to double a value. The process_array
function takes an array and a callback function as arguments, applying the callback to each element of the array.
Using Anonymous Functions as Callbacks
<?php
$array = [1, 2, 3, 4];
$result = array_map(function($value) {
return $value * 2;
}, $array);
print_r($result);
?>
Explanation: This example uses an anonymous function as a callback with the array_map
function, which applies the callback to each element of the array and returns the results.
Callback with Class Methods
<?php
class MyClass {
public function double($value) {
return $value * 2;
}
}
$instance = new MyClass();
$array = [1, 2, 3, 4];
$result = array_map([$instance, 'double'], $array);
print_r($result);
?>
Explanation: In this example, a class method double
is used as a callback function. The method is passed as an array containing the instance and method name to the array_map
function.