PHP的匿名函数

根据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
?>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值