<?php
/* 回调函数 */
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 dispatch($currentPath) {
foreach ($this->routes as $routePath => $callback) {
if ($currentPath == $routePath) {
$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();
$app->addRoute('/users/josh', function() {
// 在回调函数的上下文环境已经切换到app的实例
$this->responseContentType = 'application/json;charset=utf8';
$this->responseBody = '{"name": "yanming"}';
});
$app->dispatch('/users/josh');