浅谈PHP匿名函数和闭包(3)

class App {
 protected $routes = [];
 protected $responseStatus = '200 OK';
 protected $responseContentType = 'text/html';
 protected $responseBody = 'Laravel学院';

 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;
 }

}

这里我们需要重点关注addRoute方法,这个方法的参数分别是一个路由路径和一个路由回调,dispatch方法的参数是当前HTTP请求的路径,它会调用匹配的路由回调。第9行是重点所在,我们将路由回调绑定到了当前的App实例上。这么做能够在回调函数中处理App实例的状态:

$app = new App();
$app->addRoute(‘user/nonfu', function(){
 $this->responseContentType = ‘application/json;charset=utf8';
 $this->responseBody = ‘{“name”:”LaravelAcademy"}';
});
$app->dispatch(‘user/nonfu');
在Larval底层也有用到bindTo方法,详见Illuminate\Support\Traits\Macroable的__call方法:

以上所述是小编给大家介绍的PHP匿名函数和闭包详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对黑区网络网站的支持!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6069.html