匿名函數的簡單例子:
<?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