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)文章
php中使用exec,system等函數(shù)調(diào)用系統(tǒng)命令的方法(不建議使用,可導(dǎo)致安全問題)
PHP作為一種服務(wù)器端的腳本語言,像編寫簡單,或者是復(fù)雜的動態(tài)網(wǎng)頁這樣的任務(wù),它完全能夠勝任。但事情不總是如此,有時為了實現(xiàn)某個功能,必須借助于操作系統(tǒng)的外部程序(或者稱之為命令),這樣可以做到事半功倍2012-09-09
PHP隱形一句話后門,和ThinkPHP框架加密碼程序(base64_decode)
今天一個客戶的服務(wù)器頻繁被寫入一句話后門,刪除了還有,原來在程序中加入了如下代碼,大家可以注意下base64_decode函數(shù)的參數(shù)。2011-11-11

