6

I am new to PHP, and I tried to dynamically instantiate a class like this:

$var = new \App\$str;

But I keep getting this error:

unexpected  variable $str after '\', expected: identifier.

I know it is possible, but I am just not sure what the exact syntax is, all the examples I found are without the \App\ part which I need.

1
  • try this $var = new \App\{$str}; Commented Jan 24, 2017 at 10:36

1 Answer 1

17

The new operator accepts either a class name identifier, or a variable containing a class name, but not a mixture of them.

Since a part of your fully qualified class name is unknown (dynamic), you should put all the parts into a string variable:

$class_name = 'A';
$namespace = '\\App';
$fully_qualified_class_name = "$namespace\\$class_name";
$var = new $fully_qualified_class_name;
Sign up to request clarification or add additional context in comments.

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.