0

I have a class that I need to instantiate based on a variable passed from a form. The form either passes the string Product or Sku to my PHP script. The fully qualified class that needs to be instantiated is either:

$obj = new MyNameSpace\Product();

Or

$obj = new MyNameSpace\Sku();

I can't figure out how to properly create this namespace on the fly. I've tried the following:

$obj = new "MyNameSpace\\".$class();

Which throws this error:

PHP Parse error:  syntax error, unexpected '"MyNameSpace\\"' (T_CONSTANT_ENCAPSED_STRING)

I've read other questions and answers that say to escape the slash in order to make it a literal slash, but even that does not seem to be working for me. For example:

$class = "Product";
$string = "MyNameSpace\\".$class;
echo $string;

$string prints as MyNameSpace\\Product instead of MyNameSpace\Product. What am I missing here?

1
  • 1
    That worked, thank you! Please add that as an answer so I can accept it. Commented Jan 25, 2015 at 23:20

2 Answers 2

1

The new keyword supports only two syntaxes:

new ClassNameLiteral;

or

new $ClassNameString;

So you'll have to assemble your classname with namespace prefix beforehand:

$cn = "ns\\$class";
$obj = new $cn;
Sign up to request clarification or add additional context in comments.

Comments

0

Just do the following:

$class_name = 'Namespace\Class';
$instance = new $class_name;

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.