Callback Functions in PHP
A callback is a function that is passed as a parameter to another function.
Let's look at an example. Suppose we have a function that takes a number as its first parameter, and a callback as its second parameter:
<?php
function func($num, $calb)
{
}
?>
Let's make it so that inside the function our callback is called for the passed number:
<?php
function func($num, $calb)
{
echo $calb($num);
}
?>
Now let's see what options there are for passing a callback to our function.
Option 1
Our callback can be a regular function:
<?php
function calb($num) {
return $num ** 2;
}
?>
In this case, we pass the name of our function as the callback:
<?php
func(3, 'calb');
?>
Inside the function func
our
callback will be called by name.
Option 2
Our callback can be an anonymous function assigned to a variable:
<?php
$calb = function($num) {
return $num ** 2;
};
?>
In this case, we pass the variable containing our function as a parameter:
<?php
func(3, $calb);
?>
Option 3
You can pass an anonymous function directly as a parameter:
<?php
func(3, function($num) {
return $num ** 2;
});
?>
Option 4
You can shorten the code by using an arrow function:
<?php
func(3, fn($num) => $num ** 2);
?>
Practical Tasks
Given a function that takes an array and a callback as parameters, which will be applied to each element of the array:
<?php
function func($arr, $calb)
{
$res = [];
foreach ($arr as $elem) {
$res[] = $calb($elem);
}
return $res;
}
?>
Call this function, passing an array of numbers and a callback that squares the passed number as parameters.