I'm experimenting with PHP 5.3's namespacing functionality and I just can't figure out how to instantiate a new class with namespace prefixing.
This currently works fine:
<?php
new $className($args);
?>
But how I can prepend my namespace in front of a variable classname? The following example doesn't work.
<?php
new My\Namespace\$className($args);
?>
This example yields: Parse error: syntax error, unexpected T_VARIABLE
SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Fully qualified name. This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar . The namespace \Foo is also a fully qualified name. Relative name. This is an identifier starting with namespace , such as namespace\Foo\Bar .
Try this:
$class = "My\Namespace\\$className";
new $class();
There must be two backslashes \\
before the variable $className
to escape it
Here's how I did it:
$classPath = sprintf('My\Namespace\%s', $className);
$class = new $classPath;
Note the single quotes instead of double.
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