PHP閉包定義與使用簡單示例
本文實例講述了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 因為繼承變量的值的時候是函數(shù)定義的時候而不是 函數(shù)被調(diào)用的時候 echo $example(); //重置為hello $message = 'hello'; //此處傳引用 $example = function() use(&$message){ var_dump($message); }; echo $example(); //輸出hello $message = 'world'; echo $example(); //此處輸出world //閉包函數(shù)也用于正常的傳值 $message = 'hello'; $example = function ($data) use ($message){ return "{$data},{$message}"; }; echo $example('world'); //此處輸出world,hello
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《PHP數(shù)學(xué)運算技巧總結(jié)》及《PHP運算與運算符用法總結(jié)》、
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
WordPress中創(chuàng)建用戶角色的相關(guān)PHP函數(shù)使用詳解
這篇文章主要介紹了WordPress中創(chuàng)建用戶角色的相關(guān)函數(shù)使用,在WordPress的多用戶模式中不同角色擁有不同的權(quán)限,需要的朋友可以參考下2015-12-12PHP parse_ini_file函數(shù)的應(yīng)用與擴(kuò)展操作示例
這篇文章主要介紹了PHP parse_ini_file函數(shù)的應(yīng)用與擴(kuò)展操作,結(jié)合實例形式分析了php擴(kuò)展parse_ini_file函數(shù)解析配置文件相關(guān)操作技巧,需要的朋友可以參考下2019-01-01WordPress中Gravatar頭像緩存到本地及相關(guān)優(yōu)化的技巧
這篇文章主要介紹了WordPress中Gravatar頭像緩存到本地及優(yōu)化的技巧,需要的朋友可以參考下2015-12-12