0514-86177077
9:00-17:00(工作日)
本文實例講述了PHP閉包定義與使用。分享給大家供大家參考,具體如下:
?php function 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相關內容感興趣的讀者可查看本站專題:《php字符串(string)用法總結》、《PHP數組(Array)操作技巧大全》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》及《PHP運算與運算符用法總結》、
希望本文所述對大家PHP程序設計有所幫助。
標簽:佛山 工商登記 宿遷 宜春 澳門 常德 深圳 延安
上一篇:PHP簡單實現正則匹配省市區的方法
下一篇:php微信公眾號開發之現金紅包
Copyright ? 1999-2012 誠信 合法 規范的巨人網絡通訊始建于2005年
蘇ICP備15040257號-8