67

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

user151841
  • 17,377
  • 29
  • 109
  • 171
  • 3
    Great question and great answers. I think I sorta knew what lambda functions were and how they could be used in PHP (since I use them all the time in jQuery) but I just never wanted to think about it... kinda just actively ignored it until someone randomly asked about it. I was too lazy to verify my presumptions but accidentally finding the answer works out perfectly for me. Again... thanks. :) – KyleFarris Dec 15 '09 at 18:13
  • OK, so beyond all the hype ( "Lambda the Ultimate" ) and the fact that you can build a whole language out of lambda functions, as far as PHP goes, it's use is for a single-use, throw-away function. That's the message that I'm getting. – user151841 Dec 16 '09 at 14:40

5 Answers5

90

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;'));
Matt
  • 43,482
  • 6
  • 101
  • 102
  • Thank, Matt! Could you give an example, and why it would be better than an alternative ( unless it's apparent )? :) – user151841 Dec 15 '09 at 17:29
  • 1
    Agreed. Many of the array processing functions use callbacks, I'd be more happy being able to use an anonymous function. – ryanday Dec 15 '09 at 17:30
  • 1
    OK, I think I'm beginning to understand. If you were to use it more than once, you'd want to create a function, because the function would only get parsed once. But if you're only going to use the function once, use a lambda, because it's less overhead than a function? – user151841 Dec 15 '09 at 17:34
  • 7
    For those familiar with jQuery anonymous functions will become second nature in 5.3+ – Corey Ballou Dec 15 '09 at 17:35
  • 1
    Great answer. Though I'm feeling closure is missing there. – 7hi4g0 Nov 25 '13 at 05:31
  • The function passed to usort must return an integer representing the 3 states: equal, less, more. In this case, it would return a bool, which would probably cast to undesired integers. – delmet May 03 '15 at 19:21
12

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

GZipp
  • 5,386
  • 1
  • 22
  • 18
4

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.

Dathan
  • 7,266
  • 3
  • 27
  • 46
  • "Keep your code cleaner" this is a bit subjective tbh. I prefer a named function any day. Reading some Lambda code with "use" and params and what not and "working out" what it does, versus "getUsernameFromUserObject()". meh to anon funcs :P – James May 25 '21 at 06:38
4

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?

Community
  • 1
  • 1
7hi4g0
  • 3,729
  • 4
  • 22
  • 32
1

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

stormist
  • 5,709
  • 12
  • 46
  • 65