为什么以及如何在PHP中使用匿名函数? [英] Why and how do you use anonymous functions in PHP?

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

问题描述

PHP 5.3中提供了匿名函数.
我应该使用它们还是避免使用它们?如果可以,怎么办?

Anonymous functions are available from PHP 5.3.
Should I use them or avoid them? If so, how?

已编辑;刚刚发现了使用PHP匿名函数的一些不错的技巧...

Edited; just found some nice trick with php anonymous functions...

$container           = new DependencyInjectionContainer();
$container->mail     = function($container) {};
$conteiner->db       = function($container) {};
$container->memcache = function($container) {};

推荐答案

匿名函数在使用需要回调函数类似于 array_filter array_map 做:

Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:

$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return $val % 2 == 0; });
$arr_square = array_map(function($val) { return $val * $val; }, $arr);

否则,您将需要定义一个可能只使用一次的函数:

Otherwise you would need to define a function that you possibly only use once:

function isEven($val) { return $val % 2 == 0; }
$arr_even = array_filter($arr, 'isEven');
function square($val) { return $val * $val; }
$arr_square = array_map('square', $arr);

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

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