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

2 Answers 2

20

Try this:

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

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

Sign up to request clarification or add additional context in comments.

6 Comments

wont u need to escape the back slash? "My\\Namespace\\$className";
I don't get it... why is this necessary? I had to do the same thing. Is it something wrong with the PHP install?
The reason for the double backslash is that the backslash is a functional character and needs to be escaped itself.
Someone please explain this. Why the hell it's not possible to instantiate a namespaced class without using strings :| weird.
@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. secure.php.net/manual/en/language.namespaces.rules.php
|
1

Here's how I did it:

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

Note the single quotes instead of double.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.