PHP, new variable class in namespace

2019-06-15 01:21发布

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

2条回答
萌系小妹纸
2楼-- · 2019-06-15 02:00

Try this:

$class = "My\Namespace\$className";
new $class();
查看更多
爷的心禁止访问
3楼-- · 2019-06-15 02:06

Here's how I did it:

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

Note the single quotes instead of double.

查看更多
登录 后发表回答