BoooYaKa
BoooYaKa

Reputation: 2171

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.

Upvotes: 6

Views: 7960

Answers (1)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

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;

Upvotes: 17

Related Questions