jgivoni
jgivoni

Reputation: 1645

Instantiating class by string in current namespace

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?

Upvotes: 9

Views: 3437

Answers (1)

lonesomeday
lonesomeday

Reputation: 237817

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.

Upvotes: 13

Related Questions