本文實例講述了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/