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 '
';
$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.closure
p1p2hehe1hehe2
来源:小谈博客 http://www.tantengvip.com/2026/03/php-closure-use/
期望上述内容能对读者的PHP编程实践提供有益帮助。