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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With