本文實例講述了PHP閉包定義與使用。分享給大家供大家參考,具體如下:
<?phpfunction getClosure($i){ $i = $i.'-'.date('H:i:s'); return function ($param) use ($i) { echo "--- param: $param ---/n"; echo "--- i: $i ---/n"; };}$c = getClosure(123);$i = 456;$c('test');sleep(3);$c2 = getClosure(123);$c2('test');$c('test');/*output:--- param: test ------ i: 123-21:36:52 ------ param: test ------ i: 123-21:36:55 ------ param: test ------ i: 123-21:36:52 ---*/
再來一個實例
$message = 'hello';$example = function() use ($message){ var_dump($message);};echo $example();//輸出hello$message = 'world';//輸出hello 因為繼承變量的值的時候是函數定義的時候而不是 函數被調用的時候echo $example();//重置為hello$message = 'hello';//此處傳引用$example = function() use(&$message){ var_dump($message);};echo $example();//輸出hello$message = 'world';echo $example();//此處輸出world//閉包函數也用于正常的傳值$message = 'hello';$example = function ($data) use ($message){ return "{$data},{$message}";};echo $example('world');//此處輸出world,hello
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選