前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP闭包定义与使用简单示例

PHP闭包定义与使用简单示例

作者头像
用户8824291
修改2021-07-14 11:51:49
3540
修改2021-07-14 11:51:49
举报
文章被收录于专栏:学习乐园学习乐园

本文实例讲述了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 = getClosur/

/e(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 因为继承变量的值的时候是函数定义的时候而不是 函/

/数被调用的时候

echo $example();

//重置为hello

$message = 'hello';

//此处传引用

$example = function() use(&amp;$message){

var_dump($message);

};

echo $example();

//输出hello

$message = 'world';

echo $example();

//此处输出world

//闭包函数也用于正常的传值

$message = 'hello';

$example = function ($data) use ($message){

return "{$data},{$message}";

};

echo $example('world');

//此处输出world,hello

希望本文所述对大家PHP程序设计有所帮助。

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档