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


Dynamically create a new object from a class with different namespace

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

$api = new $controllerName($request);

行不通。因为$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');
    }
}

以及 core''controllers''lottery''ReadController 中 ReadController 的声明.php

namespace controllers'lottery;
class ReadController extends 'core'API {
}

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

谢谢!

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

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