匿名函數(shù)
匿名函數(shù)(Anonymous function),也叫閉包函數(shù)(closures)得糜,允許臨時(shí)創(chuàng)建一個(gè)沒(méi)有指定名稱的函數(shù),最經(jīng)常用作回調(diào)函數(shù)(callback)參數(shù)的值。
匿名函數(shù)的實(shí)現(xiàn)
匿名函數(shù)是目前是通過(guò)Closure類來(lái)實(shí)現(xiàn)悠垛,匿名函數(shù)會(huì)產(chǎn)生這個(gè)類的對(duì)象。自PHP 5.4起娜谊,這個(gè)類帶有一些方法确买,允許在匿名函數(shù)創(chuàng)建后對(duì)其進(jìn)行更多的控制。
注意:PHP手冊(cè)特別說(shuō)明__invoke()這個(gè)魔術(shù)方法與匿名函數(shù)的實(shí)現(xiàn)過(guò)程無(wú)關(guān)纱皆。
Closure類如下:
Closure {
/* 方法 */
__construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )
public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] )
}
Closure::__construct — 用于禁止實(shí)例化的構(gòu)造函數(shù)
Closure::bind — 復(fù)制一個(gè)閉包湾趾,綁定指定的$this對(duì)象和類作用域。
Closure::bindTo — 復(fù)制當(dāng)前閉包對(duì)象派草,綁定指定的$this對(duì)象和類作用域搀缠。
匿名函數(shù)例子:
$func = function($str){
echo $str;
};
$func('hello');
閉包
閉包是指在創(chuàng)建時(shí)封裝周圍狀態(tài)(如變量)的函數(shù),即使閉包所在的環(huán)境的不存在了近迁,閉包中封裝的狀態(tài)依然存在艺普。
閉包的實(shí)現(xiàn)
將匿名函數(shù)放在一個(gè)普通函數(shù)中(也可以將匿名函數(shù)返回),就構(gòu)成了一個(gè)閉包鉴竭。
function closureFunc(){
$func = function(){
echo 'hello';
}
$func();
}
closureFunc();//輸出:hello
閉包的使用
在匿名函數(shù)中引入局部變量時(shí)需要用到use
關(guān)鍵字歧譬。這是因?yàn)镻HP中的變量范圍只在它的生效范圍中。在匿名函數(shù)里并沒(méi)有對(duì)變量進(jìn)行定義搏存,所以需要使用use
關(guān)鍵字
function closureFunc1(){
$num = 1;
$func = function() use($num){
echo $num;
};
$func();
}
closureFunc2();//輸出
閉包返回匿名函數(shù)并傳參
function closureFunc2(){
$num = 1;
$func = function($str) use($num){
echo $num;
echo $str;
};
return $func;
}
$func = $closureFunc2();
$func('hello');//輸出 1 hello