Reputation: 189
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
Upvotes: 16
Views: 8190
Reputation: 77995
Try this:
$class = "My\Namespace\\$className";
new $class();
There must be two backslashes \\
before the variable $className
to escape it
Upvotes: 20
Reputation: 5256
Here's how I did it:
$classPath = sprintf('My\Namespace\%s', $className);
$class = new $classPath;
Note the single quotes instead of double.
Upvotes: 1