What use is lambda in PHP?

PhpLambda

Php Problem Overview


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"?

Php Solutions


Solution 1 - Php

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

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

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;'));

Solution 2 - Php

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.)

Solution 3 - Php

There are some use cases that are made more convenient by lambdas. For instance, if a method uses a callback, using a lambda for that callback means you don't have to define a "real" function somewhere to handle it. So, lambdas keep your code cleaner.

As with the above, lambdas can be used as "short-lived" functions. For instance, sorting algorithms typically only need to know if variable a is less than variable b for any combination of a and b. To make a generic sorting algorithm that's capable of handling any class of objects, you might make your sort function definition such that it accepts a function to use as a comparator. Providing a lambda as the comparator function means that you can define your sort behavior on a per-call basis, rather than having to define a "real" function that will live for the lifetime of your script just to handle this one sorting case.

Solution 4 - Php

Despite all of the uses one can think for lambda functions, in PHP it also allows something very special called closure. That is the ability to make variables in the current scope available to the function long after the current scope stops existing.

Just to mention some useful patterns that closure allow you, one can implement Memoization (Caching) and Curry.

Also very useful are the throw-away or callback functions that @Matt highlighted in his answer.

For more on closures, check this question: How do JavaScript closures work?

Solution 5 - Php

The implementation of the cryptic Y combinator?

function Y($F)
{
  $func = function ($f) { return $f($f); };
 
  return $func(function ($f) use($F)
  {
    return $F(function ($x) use($f)
    {
      $ff = $f($f);
 
      return $ff($x);
    });
  });
}

Cited Source: http://fabien.potencier.org/article/17/on-php-5-3-lambda-functions-and-closures

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser151841View Question on Stackoverflow
Solution 1 - PhpMattView Answer on Stackoverflow
Solution 2 - PhpGZippView Answer on Stackoverflow
Solution 3 - PhpDathanView Answer on Stackoverflow
Solution 4 - Php7hi4g0View Answer on Stackoverflow
Solution 5 - PhpstormistView Answer on Stackoverflow