Jfdev
Jfdev

Reputation: 189

PHP, new variable class in namespace

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

Answers (2)

JRL
JRL

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

Related Questions