Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to dynamically instantiate a class

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.

like image 433
BoooYaKa Avatar asked Dec 18 '22 10:12

BoooYaKa


1 Answers

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;
like image 104
Ruslan Osmanov Avatar answered Jan 02 '23 10:01

Ruslan Osmanov