首页 > 开发 > PHP > 正文

PHP闭包函数传参及使用外部变量的方法

2024-05-04 23:43:57
字体:
来源:转载
供稿:网友
这篇文章主要介绍了PHP闭包函数传参及使用外部变量的方法,基于Laravel框架分析了PHP闭包函数传参及外部变量相关使用技巧,需要的朋友可以参考下
 

本文实例讲述了PHP闭包函数传参及使用外部变量的方法。分享给大家供大家参考,具体如下:

在Laravel控制器写两个方法,一个是在内部创建一个闭包函数,一个是执行传过来的闭包函数,测试闭包的写法,use使用外部变量,及闭包函数的传参。如下:

//测试闭包传参及use使用外部变量public function testClosure($t1, $t2){  $closure = function ($param1, $param2) use ($t1, $t2) {    echo $param1.$param2.$t1.$t2;  };  $this->execClosure('test.closure', $closure);}//执行闭包函数protected function execClosure($name, Closure $closure){  echo 'Closure func name:'.$name;  echo '<br>';  $closure('p1', 'p2');}

在routes.php添加路由:

复制代码代码如下:
Route::get('/test/closure/{t1}/{t2}',['uses'=>'TestController@testClosure']);

 

访问www.example.com/test/closure/hehe1/hehe2

浏览器输出结果:

Closure func name:test.closurep1p2hehe1hehe2

转自:小谈博客 http://www.tantengvip.com/2016/03/php-closure-use/



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表