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

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

问题描述

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

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

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 的技术,它以非常惯用的方式大量使用 then.现在回到 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天全站免登陆