通过PHP中的变量在名称空间中调用类 [英] Calling a class in a namespace by variable in PHP

查看:321
本文介绍了通过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;

这篇关于通过PHP中的变量在名称空间中调用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆