Dynamically create a new object from a class with

2019-02-25 14:47发布

问题:

I'm trying to create a small RESTful API for my database and I encountered a problem creating controller object dynamically based on user request, because all my code is using namespaces and just doing:

$api = new $controllerName($request);

Won't work. Because $controllerName would resolve to "ReadController", but is actually \controllers\lottery\ReadController hence the error

The whole part of defining the path to the class is:

if ($method === 'GET') {
    $controllerName = 'ReadController';
    // @NOTE: $category is a part of $_GET parameters, e.g: /api/lottery <- lottery is a $category
    $controllerFile = CONTROLLERS.$category.'/'.$controllerName.'.php';
    if (file_exists($controllerFile)) {
        include_once($controllerFile);

        $api = new $controllerName($request);
    } else {
        throw new \Exception('Undefined controller');
    }
}

And the declaration of ReadController in core\controllers\lottery\ReadController.php

namespace controllers\lottery;

class ReadController extends \core\API {

}

Any ideas how to dynamically create the object?

Thanks!

回答1:

$controllerName = 'controllers\lottery\ReadController';
new $controllerName($request);

Classes instantiated from strings must always use the fully qualified class name.