php闭包学习~~

<?php
//提到闭包就不得不想起匿名函数,
//也叫闭包函数(closures),貌似PHP闭包实现主要就是靠它。声明一个匿名函数是这样:
$func=function ($value='')
{
	echo "test!!!";
};
$func();//输出test!!!
?>

闭包函数当成变量使用

<?php
//闭包函数当作变量来使用
$func_1=function ($value='')
{
	echo "This is func_1!!!";
};
$func_2=function ($value='')
{
	echo "This is func_2!!!";
};
//闭包函数当作变量来使用
function test($value){
	$value();
}
test($func_1);//输出  This is func_1!!!
test($func_2);//输出  This is func_2!!!
//或者直接传递
test(function ($value='')//输出  This is func_3!!!
{
	echo "This is func_3!!!";
});
?>
闭包函数使用外部变量:PHP在默认情况下,匿名函数不能调用所在代码块的上下文变量,而需要通过使用use关键字。

如下,会报错

<?php
//闭包函数当作变量来使用
$str='This is string';
$num=1;
$func_1=function ($value='')
{
	echo "This is func_1!!!";
	echo $str;//报错<span style="font-size:10px;">Notice: Undefined variable: str in D:\wamp\wamp\www\mytest\tp_ceshi.php on line <em>8</em></span>
	echo $num;//报错<span style="font-size:10px;">Notice: Undefined variable: num in D:\wamp\wamp\www\mytest\tp_ceshi.php on line <em>9</em></span>
};
$func_1();
?>
如下

<?php
//闭包函数使用外部变量
$str='This is string';
$num=1;
$func_1=function ($value='')use($str,$num)
{
	echo "This is func_1!!!";
	echo "<br/>";
	echo $str;
	echo "<br/>";
	echo $num;
};
$func_1();
//输出
This is func_1!!!
This is string
1
?>
闭包改变外部变量

<?php
//闭包函数使用外部变量
$str='This is string';
$num=1;
$func_1=function ($value='')use($str,$num)
{
	echo $num;
	$num++;
};
$func_1();
echo $num;
//输出结果: 1   1
?>
和一般函数一样,闭包函数不能改变外部变量的值,因为是值传递,想要改变外部变量的值,只需要在传递变量进去的时候在变量前加上"&"

<?php
//闭包函数使用外部变量
$str='This is string';
$num=1;
$func_1=function ($value='')use($str,<span style="color:#FF0000;">&$num</span>)
{
	echo $num;
	$num++;
};
$func_1();
echo $num;
<pre name="code" class="php">//输出结果: 1   2
 ?>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值