欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP閉包定義與使用簡(jiǎn)單示例

 更新時(shí)間:2018年04月13日 11:44:52   作者:程序生(Codey)  
這篇文章主要介紹了PHP閉包定義與使用,結(jié)合簡(jiǎn)單實(shí)例形式分析了php閉包的簡(jiǎn)單定義、使用方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了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 ---
*/

再來(lái)一個(gè)實(shí)例

$message = 'hello';
$example = function() use ($message){
 var_dump($message);
};
echo $example();
//輸出hello
$message = 'world';
//輸出hello 因?yàn)槔^承變量的值的時(shí)候是函數(shù)定義的時(shí)候而不是 函數(shù)被調(diào)用的時(shí)候
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è)計(jì)算法總結(jié)》、《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)》及《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論