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

jacklove
jacklove 原创
2023-04-01 20:34:02 1037浏览

这篇文章主要介绍了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 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候
echo $example();
//重置为hello
$message = 'hello';
//此处传引用
$example = function() use(&$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微信公众号开发之现金红包php实例

PHP代码重构方法漫谈_php技巧

PHP实现负载均衡下的session共用功能php技巧


以上就是PHP闭包定义与使用简单示例php技巧的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。