开发者

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 tha开发者_如何学JAVAt 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.)


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.


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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜