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

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

本文介绍了从具有不同名称空间的类动态创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

不起作用.因为$controllerName会解析为"ReadController",但实际上是\controllers\lottery\ReadController,因此会出现错误

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');
    }
}

Core \ controllers \ lottery \ ReadController.php中的ReadController声明

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?

谢谢!

推荐答案

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

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

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

这篇关于从具有不同名称空间的类动态创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:29