我正忙于一个小测试案例,并希望自己制作路线。所以当我执行www.domain.com/users
时,我想用一个名为index的方法创建一个对象。所以我可以将数据从索引方法传递给视图/模板。
如何在路线中动态获取$class->index()
?
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.'()';
}
}
}
}
答案 0 :(得分:1)
您的代码可能会被重写为:
$method = "index";
$class->$method();
另请看这里:
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"));