当前位置:首页 > PHP教程 > php应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-09-08 10:27:19 浏览: 评论:0 

这篇文章主要介绍了PHP闭包定义与使用,结合简单实例形式分析了php闭包的简单定义、使用方法及相关注意事项,需要的朋友可以参考下。

本文实例讲述了PHP闭包定义与使用,分享给大家供大家参考,具体如下:

  1. <?php 
  2. function getClosure($i) 
  3. { 
  4.   $i = $i.'-'.date('H:i:s'); 
  5.   return function ($param) use ($i) { 
  6.     echo "--- param: $param ---\n"; 
  7.     echo "--- i: $i ---\n"; 
  8.   }; 
  9. } 
  10. $c = getClosure(123); 
  11. $i = 456; 
  12. $c('test'); 
  13. sleep(3); 
  14. $c2 = getClosure(123); 
  15. $c2('test'); 
  16. $c('test'); 
  17. /* 
  18. output: 
  19. --- param: test --- 
  20. --- i: 123-21:36:52 --- 
  21. --- param: test --- 
  22. --- i: 123-21:36:55 --- 
  23. --- param: test --- 
  24. --- i: 123-21:36:52 --- 
  25. */ 

再来一个实例

  1. $message = 'hello'; 
  2. $example = function() use ($message){ 
  3.  var_dump($message); 
  4. }; 
  5. echo $example(); 
  6. //输出hello 
  7. $message = 'world'; 
  8. //输出hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候 
  9. echo $example(); 
  10. //重置为hello 
  11. $message = 'hello'; 
  12. //此处传引用 
  13. $example = function() use(&$message){ 
  14.  var_dump($message); 
  15. }; 
  16. echo $example(); 
  17. //输出hello 
  18. $message = 'world'; 
  19. echo $example(); 
  20. //此处输出world 
  21. //闭包函数也用于正常的传值 
  22. $message = 'hello'; 
  23. $example = function ($data) use ($message){ 
  24.  return "{$data},{$message}"; 
  25. }; 
  26. echo $example('world'); 
  27. //此处输出world,hello

Tags: PHP闭包定义

分享到: