';使用';在symfony应用程序中使用ReflectionClass时执行指令


'use' directive while using ReflectionClass in symfony app

我的symfony 3应用程序中有一个类,该类的方法应该使用传递给函数的名称动态实例化Model类,即:

static function getInstance($modelName){
    use $modelName;
    $r = new 'ReflectionClass($modelName);
    return $r->newInstanceArgs();
}

但是use指令中存在语法错误。

我尝试在文件顶部为每个类添加特定的use语句;我还尝试过使用require,并为相应的PHP文件提供一个完全限定的路径,但这两种方法都不起作用。

请告知如何正确执行此操作。

这个怎么样?使用限定类名

static function getInstance($modelName){
    $r = new 'ReflectionClass('AppBundle'Entity''' . $modelName);
    return $r->newInstanceArgs();
}

此外,根据PHP USE文档:

导入的范围规则

use关键字必须在文件的最外层范围(全局范围)或命名空间声明内部声明。这是因为导入是在编译时而不是运行时完成的,所以它不能是块范围的。以下示例将显示非法使用use关键字:

示例#5非法导入规则

namespace Languages;
function toGreenlandic() {
    use Languages'Danish;
}