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;//报错Notice: Undefined variable: str in D:\wamp\wamp\www\mytest\tp_ceshi.php on line <em>8</em>
    echo $num;//报错Notice: Undefined variable: num in D:\wamp\wamp\www\mytest\tp_ceshi.php on line <em>9</em>
};
$func_1();
?>
```php
如下
```php
<?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 php

标签: none

添加新评论