首頁  >  文章  >  後端開發  >  PHP閉包實戰案例使用分析

PHP閉包實戰案例使用分析

php中世界最好的语言
php中世界最好的语言原創
2018-05-16 15:58:171589瀏覽

這次帶給大家PHP閉包實戰案例使用分析,PHP閉包實戰種使用的注意事項有哪些,下面就是實戰案例,一起來看一下。

<?php
function getClosure($i)
{
  $i = $i.&#39;-&#39;.date(&#39;H:i:s&#39;);
  return function ($param) use ($i) {
    echo "--- param: $param ---\n";
    echo "--- i: $i ---\n";
  };
}
$c = getClosure(123);
$i = 456;
$c(&#39;test&#39;);
sleep(3);
$c2 = getClosure(123);
$c2(&#39;test&#39;);
$c(&#39;test&#39;);
/*
output:
--- param: test ---
--- i: 123-21:36:52 ---
--- param: test ---
--- i: 123-21:36:55 ---
--- param: test ---
--- i: 123-21:36:52 ---
*/

再來一個實例

$message = &#39;hello&#39;;
$example = function() use ($message){
 var_dump($message);
};
echo $example();
//输出hello
$message = &#39;world&#39;;
//输出hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候
echo $example();
//重置为hello
$message = &#39;hello&#39;;
//此处传引用
$example = function() use(&$message){
 var_dump($message);
};
echo $example();
//输出hello
$message = &#39;world&#39;;
echo $example();
//此处输出world
//闭包函数也用于正常的传值
$message = &#39;hello&#39;;
$example = function ($data) use ($message){
 return "{$data},{$message}";
};
echo $example(&#39;world&#39;);
//此处输出world,hello

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

php無限級評論嵌套實作步驟詳解

#PHP實作二元樹深度與廣度優先遍歷演算法步驟詳解

以上是PHP閉包實戰案例使用分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn