PHP 中的 lambda 有什么用?

发布于 2024-08-15 03:16:02 字数 176 浏览 3 评论 0原文

lambda 匿名函数是 PHP 5.3 的一部分。它有什么用呢?有什么事情只能用 lambda 来做吗? lambda 是否更适合某些任务?

我已经看过斐波那契示例,而且我真的不需要编写斐波那契序列,所以我仍然不确定它对于我在编写 webbish 应用程序时遇到的各种任务是否有用。那么人们在“现实生活”中用它做什么呢?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

庆幸我还是我 2024-08-22 03:16:02

任何需要临时功能的东西,您可能只会使用一次。

我将它们用于回调,例如以下函数:

例如

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

在 5.3 之前,你必须..

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

或 create_function ...

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

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;'));
画尸师 2024-08-22 03:16:02

匿名函数(闭包)可以创建为本地函数(因此不会污染全局空间,正如 Dathan 所建议的那样)。

使用“use”关键字,传递给封闭函数或由封闭函数创建的变量可以在闭包内使用。这对于参数列表有限的回调函数非常有用。 “使用”变量可以在闭包外部定义,从而无需在每次调用闭包时重新定义它们。

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

(当然,这个例子没有闭包可以更简单,但这只是为了演示。)

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

向地狱狂奔 2024-08-22 03:16:02

有一些用例通过 lambda 变得更加方便。例如,如果一个方法使用回调,则为该回调使用 lambda 意味着您不必在某处定义“真实”函数来处理它。因此,lambda 可以让您的代码更加简洁。

与上面一样,lambda 可以用作“短期”函数。例如,排序算法通常只需要知道对于 ab< 的任意组合,变量 a 是否小于变量 b /代码>。要创建能够处理任何类对象的通用排序算法,您可以定义排序函数,使其接受用作比较器的函数。提供 lambda 作为比较器函数意味着您可以在每次调用的基础上定义排序行为,而不必定义一个“真实”函数,该函数将在脚本的整个生命周期中存在,只是为了处理这一排序情况。

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.

新人笑 2024-08-22 03:16:02

尽管人们可以想到 lambda 函数的所有用途,但在 PHP 中它还允许一些非常特殊的东西,称为闭包。即在当前作用域停止存在后很长时间内,仍可以使当前作用域中的变量可供函数使用。

仅提一下闭包允许您使用的一些有用模式,可以实现 Memoization(缓存) 和 < a href="http://en.wikipedia.org/wiki/Currying" rel="nofollow noreferrer">咖喱。

同样非常有用的是 @Matt 在他的答案中强调的丢弃或回调函数。

有关闭包的更多信息,请检查此问题:JavaScript 闭包如何工作?

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?

⊕婉儿 2024-08-22 03:16:02

神秘的 Y 组合器的实现?

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

引用来源: http://fabien .potencier.org/article/17/on-php-5-3-lambda-functions-and-closures

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

葵雨 2024-08-22 03:16:02

您可以使用名为“array_filter”的内置 PHP 函数,而不是使用 lambda 函数。

Instead of having a lambda function you can used the builtin PHP function called "array_filter" .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文