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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2412299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:22:35  来源:igfitidea点击:

Why and how do you use anonymous functions in PHP?

phpanonymous-function

提问by Kirzilla

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

PHP 5.3 提供匿名函数。
我应该使用它们还是避免它们?如果是这样,如何?

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

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

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

回答by Gumbo

Anonymous functionsare useful when using functions that require a callback functionlike array_filteror array_mapdo:

匿名函数使用需要的函数时是有用的回调函数array_filterarray_map做:

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

回答by salathe

Anonymous functions are available from PHP 5.3.

PHP 5.3 提供匿名函数。

Anonymous functions have been available in PHP for a long time: create_functionhas been around since PHP 4.0.1. However you're quite right that there is a new concept and syntax available as of PHP 5.3.

匿名函数在 PHP 中已经存在很长时间了:create_function从 PHP 4.0.1 开始就出现了。但是,您完全正确,自 PHP 5.3 起有一个新的概念和语法可用。

Should I use them or avoid them? If so, how?

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

If you've ever used create_functionbefore, then the new syntax can simply slip right in where you used that. As other answers have mentioned, a common case is for 'throwaway' functions where they are to be used just once (or in a single place at least). Commonly that comes in the form of callbacks for the likes of array_map/reduce/filter, preg_replace_callback, usort, etc..

如果您以前使用create_function过,那么新语法可以直接插入您使用它的地方。正如其他答案所提到的,一个常见的情况是“一次性”功能,它们只使用一次(或至少在一个地方使用)。通常以回调的形式出现,例如array_map/ reduce/ filterpreg_replace_callbackusort等。

Example of using anonymous functions to count the number of times letters appear in words (this could be done in a number of other ways, it is just an example):

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

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

Which gives (snipped for brevity):

这给出(为简洁起见剪下):

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

回答by animuson

Maybe you could just read PHP's article on Anonymous Functions. It's actually pretty good.

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

回答by Kamil

Anonymous functions can be very useful in creating function into DI container too, for example "bootstrap.php":

匿名函数在将函数创建到 DI 容器中也非常有用,例如“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());

Example with usage params, and next variables

使用参数和下一个变量的示例

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

So here you can see how you can use anonymous functions to save memory and load of server. You can have defined all important plugins, classes in dicontainer, but instances will be created just if you need it.

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

回答by naivists

A typical use of anonymous functions is callback functions. For example, you could use them for callback from sort algorithms such as in function uksort( http://lv.php.net/uksort) or replacing algorithms such as preg_replace_callback( http://lv.php.net/manual/en/function.preg-replace-callback.php). Have not tried it myself in PHP, so this is just a guess.

匿名函数的典型用途是回调函数。例如,您可以将它们用于排序算法的回调,例如函数uksort( http://lv.php.net/uksort) 或替换算法preg_replace_callback( http://lv.php.net/manual/en/function .preg-replace-callback.php)。我自己没有在 PHP 中尝试过,所以这只是一个猜测。

回答by devquora

Here is sample example of using using anonymous functions in Php

这是在 PHP 中使用匿名函数的示例示例

$suppliers=['add1'=>'nodia','add2'=>'delhi', 'add3'=>'UP'];
 $getAddress = function($suppliers){ $address=[];
 for($i=1;$i<5;$i++){
  if(array_key_exists('add'.$i, $suppliers))
    $address[]=$suppliers['add'.$i];
  }
 return $address;};
 print_r($getAddress($suppliers));

In above example we have written anonymous functions that check if a key exists in inputted array. If it exists then it will put that into output array.

在上面的例子中,我们编写了匿名函数来检查输入的数组中是否存在一个键。如果它存在,那么它将把它放入输出数组。