PHP, new variable class in namespace

2019-06-15 01:45发布

问题:

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

回答1:

Try this:

$class = "My\Namespace\$className";
new $class();


回答2:

Here's how I did it:

$classPath = sprintf('My\Namespace\%s', $className);
$class = new $classPath;

Note the single quotes instead of double.