简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM