douliaotong4944 2017-11-05 13:58
浏览 46
已采纳

简单的动态路由器get方法不起作用

I am busy with a small test case and want to make my own routes. So when I execute www.domain.com/users I want to make an object with the index method called. So I can pass data from thee index method to the view/template.

How can I get $class->index() dynamically in the route?

Router::route('/users' , 'UsersController@index');
Router::execute($_SERVER['REQUEST_URI']);

class Router {

    private static $routes = array();

    private function __construct() {}
    private function __clone() {}

    public static function route($pattern, $callback) {
        $pattern = $pattern;
        self::$routes[$pattern] = $callback;
    }

    public static function execute($url) {
        foreach (self::$routes as $pattern => $callback) {
            if($pattern==$url){
                $callback = explode('@' , $callback);

                $fullclass = __NAMESPACE__ . '\\Controllers\\' . $callback[0];
                $class = new $fullclass;
                ---- Here is my problem ----
                $method = "index()";
                $class->$method.'()';
            }
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dstobkpm908182 2017-11-05 14:11
    关注

    Your code may be rewritten like this:

    $method = "index";
    $class->$method();
    

    Also have a look here:

    http://php.net/manual/en/function.call-user-func-array.php

    // Call the $foo->bar() method with 2 arguments
    $foo = new foo;
    call_user_func_array(array($foo, "bar"), array("three", "four"));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?