閉包和匿名函數在php5.3中引入,閉包是指的創(chuàng)建時封裝周圍狀態(tài)的函數,即便閉包所在的環(huán)境不存在了,閉包中封裝的狀態(tài)依然存在.匿名函數特別適合作為函數或方法回調.
首先舉一個創(chuàng)建閉包函數,并用use關鍵字來附加閉包的狀態(tài) 的demo:
function close($english_name)
{
return function ($real_name) use ($english_name) {
return $english_name . ":" . $real_name;
};
}
$close = close('season');//把字符串season封裝在閉包中
echo $close('董');//傳入參數 調用閉包
output:
season:董
首先調用close函數,需要一個$english_name的參數,這個函數返回了一個閉包對象,
這個對象有一個bindTo()方法,和__invoke()的魔術方法.
而且這個閉包封裝了$english_name參數.即使跳出了close()函數的作用域,他還是會
保存$english_name的值.(在類中以靜態(tài)屬性存放).
下面的demo演示bindTo()方法的用法:
class App{
protected $routes = [];
protected $responseStatus = '200 ok';
protected $responseContentType = 'text/html';
protected $responseBody = 'Hello World';
public function addRoute($routePath,$routeCallback)
{
$this->routes[$routePath] = $routeCallback->bindTo($this,__CLASS__);
}
public function dispath($currentPath)
{
foreach ($this->routes as $routePath=>$callback){
if ($routePath === $currentPath){
$callback();
}
}
header('HTTP/1.1 '.$this->responseStatus);
header('Content-type: '.$this->responseContentType);
header('Content-length: '.mb_strlen($this->responseBody));
echo $this->responseBody;
}
}
調用
$app = new App();
//每個閉包實例都可以使用$this關鍵字來獲取閉包內部狀態(tài)
$app->addRoute('/user/season',function (){
$this->responseContentType = 'application/json;charset=utf8';
$this->responseBody = '{"name":"season"}';
});
$app->dispath('/user/season');
注意addRoute()方法,這個方法的參數是一個路由路徑和一個路由回調.
dispath()方法的參數是當前http請求的路徑,他調用匹配的路由回調.