为什么要使用匿名函数?

发布于 2024-10-01 18:55:38 字数 319 浏览 4 评论 0原文

可能的重复:
如何在 PHP 中使用匿名函数?

为什么我应该 使用匿名函数?使用匿名函数?我的意思是,使用它的真正意义是什么? 我只是不太明白这一点。我的意思是,您使用函数使代码更干净或多次使用它。但匿名函数既不执行第一个操作,也不执行第二个操作。 我用谷歌搜索了他们,但找不到任何人问同样的问题。

Possible Duplicate:
How do you use anonymous functions in PHP?

Why should i use an anonymous function? I mean, what's the real deal using it?
I just don't really get this. I mean, you use function to make the code more clean or to use it more than once. But Anonymous functions just don't do neither the first nor the second.
I googled them and i couldn't find anyone asking the same problem.

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

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

发布评论

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

评论(9

燃情 2024-10-08 18:55:38

我想说,当有好的库类/函数使用匿名函数时,它们就会展现出它们的美丽。他们本身并不那么性感。在 .net 的世界中,有一种称为 LINQ 的技术,它以非常惯用的方式大量使用了 then。现在回到 PHP。

第一个示例,排序:

uasort($array, function($a, $b) { return($a > $b); });

您可以指定复杂的排序逻辑:

uasort($array, function($a, $b) { return($a->Age > $b->Age); });

另一个示例:

$data = array( 
        array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'), 
        array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'), 
        array('id' => 3, 'name' => 'James', 'position' => 'Director') 
); 

$names = array_map( 
        function($person) { return $person['name']; }, 
        $data 
);

您将看到如何很好地生成名称数组。

最后一项:

array_reduce(
   array_filter($array, function($val) { return $val % 2 == 0; },
   function($reduced, $value) { return $reduced*$value; }
)

计算偶数的乘积。

一些哲学。什么是函数?可调用的功能单元和代码重用单元。有时您只需要第一部分:调用和执行操作的能力,但您根本不想重用它,甚至不想让它对代码的其他部分可见。这就是匿名函数本质上所做的事情。

I would say that anonymous functions show their beauty when there is good library classes/functions that use them. They are not that sexy by themselves. In the world of .net there is technology called LINQ that makes huge use of then in very idiomatic manner. Now back to PHP.

First example, sort:

uasort($array, function($a, $b) { return($a > $b); });

You can specify complex logic for sorting:

uasort($array, function($a, $b) { return($a->Age > $b->Age); });

Another example:

$data = array( 
        array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'), 
        array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'), 
        array('id' => 3, 'name' => 'James', 'position' => 'Director') 
); 

$names = array_map( 
        function($person) { return $person['name']; }, 
        $data 
);

You see how nicely you can produce array of names.

Last one:

array_reduce(
   array_filter($array, function($val) { return $val % 2 == 0; },
   function($reduced, $value) { return $reduced*$value; }
)

It calculates product of even numbers.

Some philosophy. What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do.

最近可好 2024-10-08 18:55:38

它对于回调特别有用:

array_walk($myArray, function($value, $key) {
   // do something
});

It is useful especially for callbacks:

array_walk($myArray, function($value, $key) {
   // do something
});
机场等船 2024-10-08 18:55:38

通常,您对只需要一次的函数使用匿名函数。这样,您就不会污染函数命名空间,也不会发明像 array_walk_callback1 这样的奇怪函数名称。

You normally use anonymous functions for functions which you need only once. This way you do not pollute the function namespace and don't invent strange function names like array_walk_callback1.

谁对谁错谁最难过 2024-10-08 18:55:38

也许最明显的原因是回调的使用。以usort()函数为例。引入单行函数是没有意义的,因为它只会使用一次。匿名函数(通常)更适合这项任务。

Perhaps most obvious reason is the use of callbacks. Take usort() function for example. There's no point introducing a one-line function, that will be used once and once only. Anonymous function (usually) fits better this task.

无需解释 2024-10-08 18:55:38

您可以通过将匿名函数保存在变量中来传递它们。

$a=function() {
    echo 'hello world';
};

这意味着您还可以多次使用它们。

You can pass anonymous functions around by saving them in a variable.

$a=function() {
    echo 'hello world';
};

This means you can also use them more than once.

清君侧 2024-10-08 18:55:38

如果您需要创建一个回调(举一个具体的例子,假设它是 usort 的比较函数),匿名函数通常是一个好方法。特别是如果函数的定义依赖于一些输入(我指的是闭包,它与匿名函数不是同义)

function createCallback($key, $desc = false)
{
    return $desc ? 
       function($a, $b) use ($key) {return $b[$key] - $a[$key];} :
       function($a, $b) use ($key) {return $a[$key] - $b[$key];};
}


usort($myNestedArray, createCallback('age'));  //sort elements of $myNestedArray by key 'age' ascending
usort($myNestedArray, createCallback('age', true); //descending

If you need to create a callback (to make a concrete example, lets say its a comparison function for usort) anonymous functions are usually a good way to go. Particularly if the definition of the function is dependent on a few inputs (by this i mean a closure, which is NOT synonymous with anon function)

function createCallback($key, $desc = false)
{
    return $desc ? 
       function($a, $b) use ($key) {return $b[$key] - $a[$key];} :
       function($a, $b) use ($key) {return $a[$key] - $b[$key];};
}


usort($myNestedArray, createCallback('age'));  //sort elements of $myNestedArray by key 'age' ascending
usort($myNestedArray, createCallback('age', true); //descending
安人多梦 2024-10-08 18:55:38

有时您必须使用某个函数。因此,闭包不必用仅在一处使用的函数声明来填充您的库,从而保持代码整洁。闭包类似于 CSS 中的 style="" 和类。当然,您可以为您拥有的每一种样式创建一大堆类,或者您可以将它们嵌入到位,因为您不在其他地方使用它并减少 CSS 文件的膨胀。

不过,这不是必需的,因此如果您觉得需要显式声明函数,您可以随意这样做。

There are times when you MUST use a function. Thus closures keep code clean by not having to fill your libraries with function declarations that are only used in one place. Closures are similar to style="" and classes in CSS. Sure you can create a boatload of classes for every single one off style you have, or you can embed them in place since you do not use it elsewhere and decrease the bloat of your CSS files.

It's not a necessity, though, so if you feel the need to explicitly declare functions you are free to do that.

耳钉梦 2024-10-08 18:55:38

在我看来,匿名函数最好用作函数的回调。许多 php 数组函数 将使用这些作为参数。

它们还可以用于观察者/事件监听器模式。

In my opinion, anonymous functions are best used as callbacks for functions. Many of the php array functions will use these as parameters.

They could also be used in observer / event listener patterns.

画离情绘悲伤 2024-10-08 18:55:38

使用jQuery/Javascript,您可以使用它来定义自定义事件回调。看一下 jQuery 核心如何处理 AJAX

使用匿名函数进行事件回调的 jQuery 示例:

$.ajax({
  url: 'ajax/test.html',
  complete: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

带有自定义回调的其他事件有 beforeSenderrorsuccess。在创作自定义插件时,您可以充分利用这种灵活的事件回调系统

Using jQuery/Javascript you can use it to define custom event callbacks. Take a look at how the jQuery core handles AJAX.

Example of jQuery using anonymous functions for event callbacks:

$.ajax({
  url: 'ajax/test.html',
  complete: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

Other events w/ custom callbacks are beforeSend, error, success. You can take full advantage of this flexible event callback system when authoring custom plugins

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