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

来源:阿斌啊 发布时间:2018-12-05 15:28:30 阅读量:913

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

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<?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 ---

*/


再来一个实例


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

$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 环境搭建
分享:
评论:
你还没有登录,请先