閉包特點:
- 使用use關鍵字可以把多個關鍵字傳入閉包,此時要想像PHP函數或方法的參數一樣,使用逗號分割多個參數
- PHP閉包仍然是對象,可以使用$this關鍵字獲取閉包的內部狀態。閉包的默認狀態裏面有一個__invoke()魔術方法和bindTo()方法。
- bindTo()方法爲閉包增加了一些有趣的東西。我們可以使用這個方法把Closure對象內部狀態綁定到其他對象上。bindTo()方法的第二個參數可以指定綁定閉包的那個對象所屬的PHP類,這樣我們就可以訪問這個類的受保護和私有的成員變量。看下面的代碼示例:
class App
{
protected $route = array();
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 dispatch($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實例上,這樣就可以在回調函數中處理App實例的狀態了
$app = new App();
$app->addRoute('/users/xiaoxiao', function () {
$this->responseContentType = 'application/json;charset=utf8';
$this->responseBody = '{"name" : "xiaoxiao"}';
});
$app->dispatch('/users/xiaoxiao');