Anonymous functions are available from PHP 5.3.
Anonymous functions have been available in PHP for a long time: create_function has been around since PHP 4.0.1. However you're quite right that there is a new concept and syntax available as of PHP 5.3.
Should I use them or avoid them? If so, how?
If you've ever used create_function
before, then the new syntax can simply slip right in where you used that. As other answers have mentioned, a common case is for 'throwaway' functions where they are to be used just once (or in a single place at least). Commonly that comes in the form of callbacks for the likes of array_map/reduce/filter, preg_replace_callback, usort, etc..
Example of using anonymous functions to count the number of times letters appear in words (this could be done in a number of other ways, it is just an example):
$array = array('apple', 'banana', 'cherry', 'damson');
// For each item in the array, count the letters in the word
$array = array_map(function($value){
$letters = str_split($value);
$counts = array_count_values($letters);
return $counts;
}, $array);
// Sum the counts for each letter
$array = array_reduce($array, function($reduced, $value) {
foreach ($value as $letter => $count) {
if ( ! isset($reduced[$letter])) {
$reduced[$letter] = 0;
}
$reduced[$letter] += $count;
}
return $reduced;
});
// Sort counts in descending order, no anonymous function here :-)
arsort($array);
print_r($array);
Which gives (snipped for brevity):
Array
(
[a] => 5
[n] => 3
[e] => 2
... more ...
[y] => 1
)