PHP中的闭包(匿名函数)浅析_php技巧

WBOY
Release: 2016-05-16 20:23:59
Original
974 people have browsed it

闭包也叫匿名函数 PHP5.3 引入。

使用方法

需要调整数组元素中的值

复制代码代码如下:

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

需要改变元素的结构

复制代码代码如下:

$arr = [
[
'id'=>'',
'name'=>'',
'create_time'=>'',
],
];

$new_data = array_map(function($item) {
return ['id'=>$item['id'],'name'=>$item['name']];
}, $arr);
//如果是用foreach还需要在循环里面建立零时变量,把需要的值赋给这个变量

执行效率

复制代码代码如下:

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


经过5W次执行之后,从结果看1-3,大部分情况执行时间依次升高,其中一次执行结果时间如下
复制代码代码如下:

1:0.0260009765625
2:0.038002014160156
3:0.047003030776978

结论

闭包的代码相对优雅,但是逻辑比较容易混淆,相比其他方式执行效率相对较低,要慎用。建议在代码结构比较乱,需要封装的时候使用。

希望此文能帮到未曾使用或者对 PHP 的闭包有疑问的同学,同时如果有不对的地方欢迎支出。

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!