As anonymous functions PHP works similarly as function expressions (Function Expression) javascript.
To anonymous function is usually used as a callback but is not restricted to this, it can also be used in specific cases of your code, for example:
Perform a specific behavior within a function that will be useful only for this scope.
$addition = function($num1, $num2) {
return $num1 + $num2;
};
echo $addition(5, 5); //10
To Callback is the use of a function as a parameter of another function, allowing the use of callback as soon as necessary. A good example of using a callback is the function array_map.
public function getFilename()
{
$files = ['wallpaper', 'user-photo', 'nude'];
$appendJpg = function($name) {
return $name . '.jpg';
};
$filesJpg = array_map($appendJpg, $files);
print_r($filesJpg); //Array ( [0] => wallpaper.jpg [1] => user-photo.jpg [2] => nude.jpg )
}
Anonymous functions implemented from the PHP 5.3 version produce objects of the type Closure which offers methods for handling the function. A Closure allows inheriting variables from the parent scope (scope of the function where closure is declared) using the instruction use
.
$name = 'Victor';
$fullName = function($lastName) use ($name) {
return "$name $lastName";
};
echo $fullName('Carnaval'); //Victor Carnaval
Item 2 - How callback works in PHP,
– Valdeir Psr