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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With