匿名函数的简单例子:
<?php
$test1 = function($a){
echo $a;
};
$test1(2);
echo "\n";
$test1(3);
?>
输出 2 3
搭配use,继承父作用域的变量。使用use要注意父作用域变量的位置,必须在定义匿名函数之前,不然则会爆出“PHP Notice”
$b = "father";
$test2 = function($a) use ($b){
echo $a." ".$b;
};
$test2("I love");
输出 I love father
use继承并使用引用&
$b = 1;
$test3 = function($a) use (&$b){
echo $a * $b;
$b++;
};
$test3(2);
echo "\n";
$test3(2);
输出: 2 4
在外部重新定义$b,结果也是一样
<?php$b = 1;
$test3 = function($a) use (&$b){
echo $a * $b;
};
$test3(2);
$b = 4;
echo "\n";
$test3(2);
?>
输出: 2 4
类中定义匿名函数
<?php
class D{
protected $num = 2;
public function test4(){
$func = function(){
echo $this->num++;
};
return $func();
}
}
$Dtest = new D();
$Dtest->test4();
echo "\n";
$Dtest->test4();
?>
输出:2 3