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

PHP闭包函数传参及使用外部变量的方法。具体如下:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//测试闭包传参及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

浏览器输出结果:

1
2
Closure func name:test.closure
p1p2hehe1hehe2
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发

请登录后发表评论