PHP 5.3 Introduction to Anonymous Functions


New to PHP 5.3 is the introduction of anonymous function. Anonymous functions also known as closures are methods that do not require a specified name to be assign to a function.

Prior to 5.3

function firstName($name) {
   echo $name;

Now using anonymous function

$firstName = function($name) {
    echo $name;

As you can see we are accomplishing the same tasks, however the anonymous function method do become useful if you wish to write them for definitions of other methods.

Take for example that we want to filter out all values that do not equal 3 or 4.

$myDefinition = function ($v) {
            return ($v == 3 || $v == 4);
$values = array(23, 34, 4, 12, 6);
$output = array_values(array_filter($values, $myDefinition));

The result is as expected.

	(int) 0 => (int) 4