从具有不同命名空间的类动态创建新对象

deb*_*ian 2 php oop namespaces

我正在尝试为我的数据库创建一个小的RESTful API,我遇到了一个基于用户请求动态创建控制器对象的问题,因为我的所有代码都在使用命名空间,只是这样做:

$api = new $controllerName($request);
Run Code Online (Sandbox Code Playgroud)

不行.因为$controllerName会解析为"ReadController",但实际上\controllers\lottery\ReadController是错误

定义类的路径的整个部分是:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

并在core\controllers\lottery\ReadController.php中声明ReadController

namespace controllers\lottery;

class ReadController extends \core\API {

}
Run Code Online (Sandbox Code Playgroud)

任何想法如何动态创建对象?

谢谢!

dec*_*eze 8

$controllerName = 'controllers\lottery\ReadController';
new $controllerName($request);
Run Code Online (Sandbox Code Playgroud)

从字符串实例化的类必须始终使用完全限定的类名.