Anonymous functions (Anonymous functions), also called closure functions, allow temporarily creating a function without a specified name. The value most often used as the callback function (callback) parameter. Of course, there are other applications as well.
Anonymous functions are currently implemented through the Closure class.
Closure functions can also be used as the value of variables. PHP will automatically convert this expression into an object instance of the built-in class Closure. The method of assigning a closure object to a variable is the same as the syntax of ordinary variable assignment, and a semicolon must be added at the end:
This article mainly introduces closures in PHP (Anonymous Function) Brief analysis, this article gives a usage example and execution efficiency test, friends in need can refer to the
usage method
needs to adjustIntegerThe value in the group element
The code is as follows:
$data = range(0, 100);//想要每个元素的值都加上.html的后缀 $suffix = '.html'; function makeSuffix($str, $suffix) { return $str . $suffix; } $new_data = array_map(function($item) use ($suffix) { return makeSuffix($item, $suffix); }, $data);
Need to change the structure of the element
$arr = [ [ 'id'=>'', 'name'=>'', 'create_time'=>'', ], ]; $new_data = array_map(function($item) { return ['id'=>$item['id'],'name'=>$item['name']]; }, $arr);
foreach, you also need to create a zero-time variable in the loop and assign the required value to this Variable
Execution efficiency
$data = range(0, 50000) //1 foreach ($data as &$value) { $value = makeSuffix($value, $suffix); } //2 foreach ($data as $value) { $new[] = makeSuffix($value, $suffix); } //3 array_map(function($item) use ($suffix) { return makeSuffix($item, $suffix); }, $data);
1:0.0260009765625 2:0.038002014160156 3:0.047003030776978
Conclusion
Closed The code is relatively elegant, but the logic is easily confused and the execution efficiency is relatively low compared to other methods, so use it with caution. It is recommended to use it when the code structure is messy and needs to be encapsulated.The above is the detailed content of A brief introduction to anonymous functions in php. For more information, please follow other related articles on the PHP Chinese website!