Anonymous Functions

Some PHP functions use a function you provide them with to do part of their work. For example, the usort() function uses a function you create and pass to it as a parameter to determine the sort order of the items in an array.

Although you can define a function for such purposes, as shown previously, these functions tend to be localized and temporary. To reflect the transient nature of the callback, create and use an anonymous function (also known as a closure).

You can create an anonymous function using the normal function definition syntax, but assign it to a variable or pass it directly.

Example 3-6 shows an example using usort().

Example 3-6. Anonymous functions

$array = array("really long string here, boy", "this", "middling length", "larger");

usort($array, function($a, $b) {
  return strlen($a) - strlen($b);
});

print_r($array);

The array is sorted by usort() using the anonymous function, in order of string length.

Anonymous functions can use the variables defined in their enclosing scope using the use syntax. For example:

$array = array("really long string here, boy", "this", "middling length", "larger");
$sortOption = 'random';

usort($array, function($a, $b) use ($sortOption)
{
  if ($sortOption == 'random') {
    // sort randomly by returning (−1, 0, 1) at random
    return rand(0, 2) - 1;
  }
  else {
    return strlen($a) - strlen($b);
  }
});

print_r($array);

Note that incorporating variables from the enclosing scope is not the same as using global variables—global variables are ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.