PHP Callback Functions are an essential feature of PHP programming language. They are used to pass a function as an argument to another function. Callback functions are also known as higher-order functions. They are used to create more flexible and reusable code.
Callback functions are used in many PHP functions, such as array_map(), array_filter(), and usort(). These functions take a callback function as an argument and apply it to each element of an array. The callback function is called for each element of the array and returns a value that is used to create a new array.
Callback functions can be defined in two ways: as a named function or as an anonymous function. A named function is a function that has a name and can be called by its name. An anonymous function is a function that does not have a name and is defined inline.
Here is an example of a named function:
function add($a, $b) {
return $a + $b;
}
function multiply($a, $b) {
return $a * $b;
}
function calculate($a, $b, $callback) {
return $callback($a, $b);
}
$result = calculate(2, 3, 'add');
echo $result; // Output: 5
$result = calculate(2, 3, 'multiply');
echo $result; // Output: 6
In this example, we have defined three functions: add(), multiply(), and calculate(). The calculate() function takes three arguments: $a, $b, and $callback. The $callback argument is a callback function that is called with $a and $b as arguments. The add() and multiply() functions are passed as callback functions to the calculate() function.
Here is an example of an anonymous function:
function calculate($a, $b, $callback) {
return $callback($a, $b);
}
$result = calculate(2, 3, function($a, $b) {
return $a + $b;
});
echo $result; // Output: 5
$result = calculate(2, 3, function($a, $b) {
return $a * $b;
});
echo $result; // Output: 6
In this example, we have defined the calculate() function that takes three arguments: $a, $b, and $callback. The $callback argument is an anonymous function that is defined inline. The anonymous function is called with $a and $b as arguments. The add() and multiply() functions are defined inline as anonymous functions and passed as callback functions to the calculate() function.
PHP Callback Functions are a powerful feature of PHP programming language. They allow us to create more flexible and reusable code. Callback functions can be defined as named functions or anonymous functions. They are used in many PHP functions, such as array_map(), array_filter(), and usort().