为什么以及如何在PHP中使用匿名函数?

匿名函数可以从PHP 5.3中获得。
我应该使用它们还是避免它们? 如果是这样,怎么样?

编辑 ; 刚发现一些不错的技巧与PHP匿名函数…

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

当使用需要像array_filterarray_map这样的callback函数的函数时, 匿名函数很有用:

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

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

 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 5.3中获得。

PHP中的匿名函数已经有很长一段时间了:自PHP 4.0.1起, create_function就已经存在了。 不过,PHP5.3中有一个新的概念和语法是非常正确的。

我应该使用它们还是避免它们? 如果是这样,怎么样?

如果你以前曾经使用过create_function ,那么新的语法就可以直接放在你使用的地方。 正如其他答案所提到的,一个常见的情况是“一次性使用”function,只能使用一次(或者至less在一个地方使用)。 通常这是以array_map / reduce / filter , preg_replace_callback , usort等等的callbackforms出现的。

使用匿名函数来计算字母出现在单词中的次数的示例(这可以通过其他方式进行,这仅仅是一个示例):

 $array = array('apple', 'banana', 'cherry', 'damson'); // For each item in the array, count the letters in the word $array = array_map(function($value){ $letters = str_split($value); $counts = array_count_values($letters); return $counts; }, $array); // Sum the counts for each letter $array = array_reduce($array, function($reduced, $value) { foreach ($value as $letter => $count) { if ( ! isset($reduced[$letter])) { $reduced[$letter] = 0; } $reduced[$letter] += $count; } return $reduced; }); // Sort counts in descending order, no anonymous function here :-) arsort($array); print_r($array); 

这给出了(为了简洁起见):

 Array ( [a] => 5 [n] => 3 [e] => 2 ... more ... [y] => 1 ) 

也许你可以阅读关于匿名函数的 PHP文章。 这其实很不错

匿名函数在DI容器中创build函数也是非常有用的,比如“bootstrap.php”:

 //add sessions $di->add("session",function(){ return new Session(); }); //add cache $di->add("cache",function(){ return new Cache(); }); //add class which will be used in any request $di->add("anyTimeCalledClass", new SomeClass()); 

使用参数和下一个variables的示例

 $di->add("myName",function($params) use($application){ $application->myMethod($params); }); 

所以在这里您可以看到如何使用匿名函数来节省内存和服务器负载。 你可以定义所有重要的插件,在容器中的类,但是实例将在你需要的时候被创build。

匿名函数的典型用法是callback函数。 例如,您可以使用它们从sortingalgorithm中进行callback,例如在函数uksorthttp://lv.php.net/uksort )中,或者replace诸如preg_replace_callbackhttp://lv.php.net/manual/en /function.preg-replace-callback.php )。 还没有尝试过自己在PHP中,所以这只是一个猜测。