16

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

hakre
  • 193,403
  • 52
  • 435
  • 836
Jfdev
  • 189
  • 1
  • 5

2 Answers2

20

Try this:

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

There must be two backslashes \\ before the variable $className to escape it

sMyles
  • 2,418
  • 1
  • 30
  • 44
JRL
  • 76,767
  • 18
  • 98
  • 146
  • 2
    wont u need to escape the back slash? "My\\Namespace\\$className"; – Stevanicus May 16 '12 at 18:58
  • I don't get it... why is this necessary? I had to do the same thing. Is it something wrong with the PHP install? – Big McLargeHuge Aug 01 '12 at 23:25
  • The reason for the double backslash is that the backslash is a functional character and needs to be escaped itself. – Dandy Sep 29 '12 at 16:45
  • 1
    Someone please explain this. Why the hell it's not possible to instantiate a namespaced class without using strings :| weird. – Stichoza Nov 21 '13 at 01:17
  • @Stichoza it is possible, but in the question asked OP is mixing a namespace with a string which makes no sense, why would php expect a random string dropped into the middle of the line. https://secure.php.net/manual/en/language.namespaces.rules.php – Shardj Sep 24 '18 at 10:24
  • Yes the backslash before `$className` must be escaped – sMyles Oct 10 '19 at 15:26
1

Here's how I did it:

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

Note the single quotes instead of double.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57