您好我正在尝试在php中实现一个熟悉express.js的url路由器 这是我到目前为止的代码。
class Router{
private $request;
private $request_params;
private $params_num;
private $paths;
public function __construct(){
$this->paths = array();
$this->request = strtolower($this->hookRequest());
if ($this->request != false){
$this->request_params = $this->hookRequestParams();
} else {
$this->request_params = array('home');
}
}
public function __destruct(){
foreach($this->paths as $key => $value){
if($this->getRequest() == $key){
$value();
}
}
}
public function get($path, $func){
$this->paths[$path] = $func;
}
private function hookRequest(){
return isset($_GET['req']) ? rtrim($_GET['req'], '/') : false;
}
private function hookRequestParams(){
$params = explode('/', $this->request);
$this->params_num = count($params);
return $params;
}
public function getRequest(){
return $this->request;
}
public function getRequestParams(){
return $this->request_params;
}
public function getPage(){
return $this->request_params[0];
}
public function getAction(){
if($this->params_num > 1){
return $this->request_params[1];
}
return false;
}
public function getActionParams(){
if($this->params_num > 2){
return $this->request_params[2];
}
return false;
}
}
这可以像你想象的那样使用:
$router = new Router();
$router->get('index', function(){
echo 'index'; //index is being shown to the browser as expectd
echo $this->getPage(); // This does not work apparently
})
我的问题是如何在匿名函数中执行$ router方法?
如此示例中显示$this->getPAge();
答案 0 :(得分:4)
使用闭包..
$router->get('index', function() use ($router) {
echo 'index';
echo $router->getPage();
})
如果您在班级中定义了Closure,那么这应该是有用的。