Reputation: 2400
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.'()';
}
}
}
}
Upvotes: 0
Views: 60
Reputation: 347
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"));
Upvotes: 1