Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating class by string in current namespace

Tags:

namespaces

php

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?

like image 828
jgivoni Avatar asked May 29 '12 12:05

jgivoni


People also ask

How to modify a string without creating a new object?

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

How to use StringBuilder class in net?

Using the StringBuilder Class in .NET. The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object.

Why do I have to create a new string every time?

Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

How do I create a new StringBuilder in Java?

To avoid having to provide a fully qualified type name in your code, you can import the System.Text namespace: You can create a new instance of the StringBuilder class by initializing your variable with one of the overloaded constructor methods, as illustrated in the following example.


1 Answers

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.

like image 52
lonesomeday Avatar answered Nov 06 '22 06:11

lonesomeday