Home  >  Article  >  Backend Development  >  A brief analysis of closures (anonymous functions) in PHP, a brief analysis of php_PHP tutorial

A brief analysis of closures (anonymous functions) in PHP, a brief analysis of php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:07:41951browse

A brief analysis of closures (anonymous functions) in PHP, a brief analysis of php

Closure is also called anonymous function and was introduced in PHP5.3.

How to use

Need to adjust the values ​​in the array elements

Copy code The code is as follows:

$data = range(0, 100);//You want the value of each element to be added 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

Copy code 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 are using foreach, you need to create a zero-time variable in the loop and assign the required value to this variable

Execution efficiency

Copy code The code is as follows:

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


After 5W executions, looking at the results 1-3, the execution time in most cases increases sequentially. One of the execution result times is as follows
Copy code The code is as follows:

1:0.0260009765625
2:0.038002014160156
3:0.047003030776978

Conclusion

The closure code is relatively elegant, but the logic is easy to confuse, and its execution efficiency is relatively low compared to other methods, so it should be used with caution. It is recommended to use it when the code structure is messy and needs to be encapsulated.

I hope this article can help students who have never used it or have questions about PHP closures. If there is something wrong, please feel free to comment.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/954659.htmlTechArticleA brief analysis of closures (anonymous functions) in PHP, a brief analysis of php closures are also called anonymous functions PHP5.3 Introduction. Usage: You need to adjust the values ​​in the array elements. Copy the code. The code is as follows: $data = rang...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn