Anonymous functions are useful when you want to pass them around as arguments to other functions (higher order functions). To PHP they are relatively new, even if they should probably have existed long before. Let's implement something like reduce in PHP.
Reduce calls a function for each element in an array, passing it two arguments each time it is invoked. The first argument is a memo variable, that is the result of each invocation of the anonymous function thus far. The second argument is the value of the current element in the array. The overall output is a single value computed by performing the same operation across all adjacent elements in the array. This will make more sense in code.
We'll pretend that PHP's array_reduce() function doesn't already exist

$fn in the reduce() function is an anonymous function; reduce() cannot work without it, since it provides half of its implementation.
Code: Select all
<?php
function reduce($array, $fn) {
if (count($array) < 2) {
return current($array); // special case
}
$memo = array_shift($array); // initial memo value is the first element
foreach ($array as $value) {
$memo = $fn($memo, $value); // memo is updated according to $fn for each element
}
return $memo;
}
This function cannot work without the help of some other function, because it makes no assumptions about how to actually reduce the array. Lets go with a simple example that just adds all the numbers in an array together:
Code: Select all
echo reduce(array(1, 2, 3), function ($a, $b) { return $a + $b }); // 6
The function $fn was first invoked with 1 and 2, so it returned 3. Then it was invoked with the same 3 and the 3 that is left in the array, so it returned 6. Because no data was left in the array, 6 was returned from reduce().
How about using reduce to implement something like PHP's implode() function? We can do that, because we specify the behaviour via our anonymous function!
Code: Select all
echo reduce(array("eggs", "bacon", "tomatoes"), function ($a, $b) { return "$a and $b"; }); // eggs and bacon and tomatoes
These types of higher order functions are commonplace in functional programming languages like Lisp, Scheme and Haskell, which are based entirely around lambda calculus and thus depend heavily on functions to implement algorithms as basic as iteration data structures.
If the concept interests you, here's an implementation of map in Scheme, which applies the function map-fn to each expression in the list lst. Scheme is entirely driven by lists and functions. The variable name map-fn here is just a name. The actual function can either be anonymous (lambda), or a defined function with another name. The name is unimportant, since it is just a reference to the function, so it can be applied.
Code: Select all
(define (map lst map-fn)
(cond
((null? lst) '())
(else
(cons (map-fn (car lst))
(map (cdr lst) map-fn)))))