通过PHP中的变量在名称空间中调用类

通过PHP中的变量在名称空间中调用类

问题描述:

我有一个函数,该函数仅基于给定记录ID的一组记录显示一个表.然后,该函数通过从参数数组中拉出的变量来调用类.效果很好...

I have a function that displays a table based on a set of records given the id of the records only. The function then calls the class by variable pulled from an array of parameters. This worked just fine...

function displayTable($arr) {
...
    foreach ($a['ids'] as $key => $arr) 
    {
        $m=$a['model'];
        $o = new $m($arr['id']);
    ...
    }
}

问题是我现在将类放在名称空间中,以下内容不起作用并引发错误...

The issue is I now have the class in a namespace and the following does not work and throws an error...

function displayTable($arr) {
...
    foreach ($a['ids'] as $key => $arr) 
    {
        $m=$a['model'];
        $o = new \My\New\Namespace\$m($arr['id']);
    ...
    }
}

解析错误:语法错误,意外的'$ m'(T_VARIABLE),期望的标识符(T_STRING)

Parse error: syntax error, unexpected '$m' (T_VARIABLE), expecting identifier (T_STRING)

我该怎么做?

在对象初始化之前,只需将名称空间添加到变量之前即可.

Just prepend namespace to variable, before object initialization:

$m = '\\My\\New\\Namespace\\' . $m;