您的位置:首页 > 编程语言 > PHP开发

什么是PHP闭包???

2016-06-28 16:05 597 查看

闭包函数:临时创建一个没有名称的函数,经常作为回调函数来用。

通俗的说就是:子函数可以使用父函数中的局部变量,这种行为叫做闭包。

1、匿名函数赋值

  $demo=function($str){

    echo $str;

  }

  $demo('hello,world');

 

2、闭包可以从父作用域中继承变量,任何此类型变量都应该用use语言结构传递进去。

  $message='hello';

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

    var_dump($message);

  };

  echo $example();

  结果:hello;

 

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

    var_dump($message);

  }

  echo $example();

  结果:hello;

 

  $message='world';

  echo $example();

  结果:world;

 

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

    var_dump($arg.' '.$message);

  }

  $example('hello');

  结果:hello world;

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: