PHP5.3之后引入了闭包函数的特性,又称为匿名函数。下面介绍几种常用的用法:
1.直接使用:
<?php
$f = function($s)
{
echo $s;
}; //这个分号不能丢,否则会报错
$f('HELLO');
- 在函数中使用闭包
<?php
function test()
{
$f = function ($s)
{
echo $s;
};
$f('HELLO');
}
test();
复制代码
3.用作函数的返回值
<?php
function test(){
$f = function($s)
{
echo $s;
};
return $f;
}
$r = test();
$r('HELLO')
如果想引用闭包所在代码块上下文的变量,可以使用关键字USE,举例:
<?php
function test(){
$a = 1;
$b = 2;
$f = function() use($a, $b){
echo $a;
echo $b;
}
}
test();