为什么以及如何在 PHP 中使用匿名函数? [英] Why and how do you use anonymous functions in PHP?
本文介绍了为什么以及如何在 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屋!
查看全文