What use is lambda in PHP?

The lambda anonymous function is part of PHP 5.3. What use does it have? Is there anything that one can only do with lambda? Is lambda better for certain tasks?

I've seen the Fibonacci example, and I really don't need to write Fibonacci sequences, so I'm still not sure if it's that useful for the kinds of tasks I encounter in writing webbish applications. So what does one do with it in "real life"?


Anything that requires a temporary function that you probably will only use once.

I would use them for callbacks, for functions such as:

  • usort
  • preg_replace_callback

E.g.

usort($myArray, function ($a, $b) {
    return $a < $b;
});

Before 5.3, you'd have to..

function mySort ($a, $b) {
    return $a < $b;
}
usort($myArray, 'mySort');

Or create_function ...

usort($myArray, create_function('$a, $b', 'return $a < $b;'));

Anonymous functions (closures) can be created as local functions (thus not pollluting the global space, as Dathan suggested).

With the "use" keyword, variables that are passed to or created by the enclosing function can be used inside the closure. This is very useful in callback functions that are limited in their parameter list. The "use" variables can be defined outside the closure, eliminating the need to redefine them each time the closure is called.

function change_array($arr, $pdo)
{
    $keys = array('a', 'c');
    $anon_func = function(& $val, $key) use ($keys, $pdo)
    {
         if (in_array($key, $keys) {
            $pdo->query('some query using $key');
            $val = $pdo->fetch();
        }
    }
    arr_walk($arr, $anon_func);
    return $arr;
}

$pdo = new($dsn, $uname, $pword);
$sample = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$sample = change_array($sample, $pdo);

(Of course, this example can be simpler without a closure, but it's just for demo.)