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

不言
发布: 2023-03-23 17:22:02
原创
1482 人浏览过

这篇文章主要介绍了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.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!