匿名函數(shù)(Anonymous functions)芯侥,也叫閉包函數(shù)(closures)洛心,允許 臨時創(chuàng)建一個沒有指定名稱的函數(shù)。最經(jīng)常用作回調(diào)函數(shù)(callback)參數(shù)的值梗醇。
變量賦值
閉包函數(shù)可以作為變量的值使用鳄抒,最后需要加分號闯捎。
$test = function ($var) {
echo $var;
};
$test('hello');
$test('world');
回調(diào)函數(shù)參數(shù)
example1:
function myfunction($v)
{
return($v*$v);
}
$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));//1,4许溅,9瓤鼻,16,25
example2:
$test = ['a' => 1, 'b' => 2];
$res = array_map(function ($item) {
$item = 3;
return $item;//注意贤重,一定要有return
}, $test);
echo $res;//['a'=>3,'b'=>3]
父作用域繼承變量
閉包想要使用父作用域中的變量需要使用use關(guān)鍵字茬祷,匿名函數(shù)不會自動從父作用域中繼承變量。
$var = "hello";
$test = ['apple', 'orange'];
$res = array_map(function ($item) use ($var) {
$item = $var . ',' . $item;
return $item;
}, $test);
print_r($test);//["hello,apple","hello,orange"]
use中還可以使用引用變量
$var = 1;
$test = [1, 2, 3];
$res = array_map(function ($item) use (&$var) {
$var += $item;
return $item;
}, $test);
echo $var;//7