根据PHP官方文档的解释:匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。
具体使用实例如下:
一、作为一个回调函数
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
//模式~-([a-z])~会匹配到 -w ,但是有括号会有一个子模式,匹配到w, $match[0]是-w而$match[1]则是w
//把匹配到的全模式替换成return 后面的
?>
<?php
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
echo preg_replace_callback('#(\d{2}/\d{2}/)(\d{4})#', function ($match) {
return $match[1].($match[2]+1);
}, $text);
// 输出 April fools day is 04/01/2003 Last christmas was 12/24/2002
?>
二、匿名函数变量赋值
<?php
$helloworld=function($var){
return $var."anonymousfunctions";
};
echo $helloworld("helloworld");
?>
三、匿名函数引入全局变量
默认情况下在匿名函数中,打印全局变量是无效的(Notice: Undefined variable)必须要use一下
<?php
$value="helloworld";
$helloworld=function($var) use ($value){
return $var.$value;
};
echo $helloworld("helloworld");
//helloworldhelloworld
?>