为什么使用匿名函数? [英] Why use anonymous function?

查看:415
本文介绍了为什么使用匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在PHP中使用匿名函数?

为什么要使用匿名函数?我的意思是,什么是真正的协议使用它?
我只是不是真的得到这个。我的意思是,你使用函数,使代码更干净或使用它不止一次。但匿名函数不是既不做第一也不做第二。
我google了他们,我找不到任何人问同样的问题。

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.

推荐答案

我会说匿名函数当有好的库类/函数使用它们时,显示他们的美。他们自己不是那么性感。在.net的世界里有一种名为LINQ的技术,它以非常惯用的方式大量使用。现在回到PHP。

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.

第一个例子,排序:

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

另一个例子:

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

上一个:

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

它计算偶数的乘积。

一些哲学 ?可以被调用的功能单元和代码重用单元有时你只需要第一部分:调用和执行动作的能力,但是你不想重用它,甚至让其他部分可见代码,这是匿名函数本质上做的。

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.

这篇关于为什么使用匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆