在类名中使用变量? [英] Using a variable in a class name?

查看:94
本文介绍了在类名中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我定义了一些名称空间,并且我想实例化这样的新对象:

so I have some namespaces defined and I wand to instance new objects like this:

$this->controller = new \controller\$this->controller($this->cfg);

但我得到

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

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

我该如何进行这项工作?

How can I make this work?

推荐答案

您似乎正在尝试动态确定要实例化的对象的类名称.为此,您可以创建一个包含带有类名字符串的变量,然后实例化该变量:

It looks like you're trying to dynamically determine the class name of the object to instantiate. To do this, you can create a variable that contains a string with the class name, and then instantiate on that variable:

$string = $someObject->someMethod();
$class = '\\controller\\' . $string;
$newObject = new $class();

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

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