PHP閉包定義與使用簡單示例
更新時間:2018年04月13日 11:44:52 作者:程序生(Codey)
這篇文章主要介紹了PHP閉包定義與使用,結合簡單實例形式分析了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ù)被調用的時候
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
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php字符串(string)用法總結》、《PHP數(shù)組(Array)操作技巧大全》、《PHP數(shù)據(jù)結構與算法教程》、《php程序設計算法總結》、《PHP數(shù)學運算技巧總結》及《PHP運算與運算符用法總結》、
希望本文所述對大家PHP程序設計有所幫助。
相關文章
WordPress中創(chuàng)建用戶角色的相關PHP函數(shù)使用詳解
這篇文章主要介紹了WordPress中創(chuàng)建用戶角色的相關函數(shù)使用,在WordPress的多用戶模式中不同角色擁有不同的權限,需要的朋友可以參考下2015-12-12
PHP parse_ini_file函數(shù)的應用與擴展操作示例
這篇文章主要介紹了PHP parse_ini_file函數(shù)的應用與擴展操作,結合實例形式分析了php擴展parse_ini_file函數(shù)解析配置文件相關操作技巧,需要的朋友可以參考下2019-01-01
WordPress中Gravatar頭像緩存到本地及相關優(yōu)化的技巧
這篇文章主要介紹了WordPress中Gravatar頭像緩存到本地及優(yōu)化的技巧,需要的朋友可以參考下2015-12-12

