• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP闭包函数

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

PHP>v5.3闭包函数,闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函数来处理

匿名函数也叫闭包函数(closures允许创建一个没有指定没成的函数,最经常用作回调函数参数的值。

闭包函数没有函数名称,直接在function()传入变量即可 使用时将定义的变量当作函数来处理。

闭包内部函数使用了外部函数中定义的变量.在PHP新开放的闭包语法中, 我们就是用use来使用闭包外部定义的变量的。

正常函数:

  function  cl($name){
       return sprintf('hello %s',$name);
  }

打印:

echo cl('world');

结果:hello world

匿名函数:

  $cl = function($name){
    return sprintf('hello %s',$name);
  };
  echo $cl('world');

结果:hello world

打印$cl 类型

object(Closure)#1 (1) {
  ["parameter"]=>
  array(1) {
    ["$name"]=>
    string(10) ""
  }
}

直接通过定义为匿名函数的变量名称来调用

echo preg_replace_callback('~-([a-z])~', function ($match) {
  return strtoupper($match[1]);
}, 'hello-world');

结果:helloWorld

使用use

$message = 'hello';
$example = function() use ($message){
  var_dump($message);
};
echo $example();

 

结果:string(5) "hello"

带参数:

$message = 'hello';
$example = function ($data) use ($message){
  return "{$data},{$message}";
};

echo $example('world');

结果:world,hello

 

闭包不会改变外部变量

$message = 'hello';
$test = function () use ($message){
 var_dump($message);
 $message = 'Hi……';
};
$test();   

$message = 'Ni Hao!';
$test(); 

结果:

string(5) "hello"
string(5) "hello"

 

转载来自:http://www.phperz.com/article/16/0227/190900.html

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP的学习路线?如何系统且高效地学习发布时间:2022-07-10
下一篇:
[保留] PHP日期处理的经典贴子(转载)发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap