This article mainly introduces the closure (anonymous function) in PHP, this paper gives a use of examples and execution efficiency test, the need for friends can refer to the following
Closures are also called anonymous function PHP5.3 introduced.
How to use
You need to adjust the values in the array elements
The code is as follows:
$data = Range (0, 100);//You want the value of each element to be appended with the. html suffix $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
The code is as follows:
$arr = [[' id ' = ' = ', ' name ' = = ', ' create_time ' = ', '], ' ; $new _data = Array_map ( function ($item) { return [' id '] = $item [' id '], ' name ' = + $item [' name '];}, $arr);//If you use foreach, you need to set the zero , assign the required value to the variable
Execution efficiency
The code is as follows:
$data = Range (0, 50000)//1foreach ($data as & $value) { $value = Makesuffix ($value, $suffix);} 2foreach ($data as $value) { $new [] = Makesuffix ($value, $suffix);} 3array_map (function ($item) use ($suffix) { return Makesuffix ($item, $suffix);}, $data);
After 5W execution, from the results of 1-3, most of the time the execution times are increased, one of the results of the execution time is as follows
The code is as follows:
1:0.02600097656252:0.0380020141601563:0.047003030776978
Conclusion
The code for closures is relatively elegant, but logic is easier to confuse and less efficient to implement than other methods, so use caution. It is recommended to use when the code structure is messy and needs to be encapsulated.