1

您好,我正在尝试在 php 中实现一个 url 路由器,这是 express.js 熟悉的东西 这是我到目前为止的代码。

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();

4

1 回答 1

4

使用闭包..

$router->get('index', function() use ($router) {
    echo 'index';
    echo $router->getPage();
})

如果你在你的类中定义你的闭包, $this 应该是可行的。

于 2013-09-21T20:46:57.173 回答