Instantiating class by string in current namespace

百般思念 提交于 2021-02-06 11:21:35

问题


I'm trying to instantiate an object of a dynamically created classname. I'm using namespaces and the class I want to instantiate is in the same namespace.

To examplify, this works fine:

namespace MyNamespace;

new MyClass; // MyNamespace\MyClass instantiated

Whereas this doesn't:

namespace MyNamespace;

$class = 'MyClass';
new $class; // Class 'MyClass' not found

Is this a bug or am I doing something wrong?


回答1:


When you use a string with new you need to provide a fully qualified class name.

You can do this with __NAMESPACE__:

$fullclass = __NAMESPACE__ . '\\' . $class;
new $fullclass;

See the documentation for the new operator and the __NAMESPACE__ magic constant.



来源:https://stackoverflow.com/questions/10799552/instantiating-class-by-string-in-current-namespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!