Home >Backend Development >PHP Tutorial >How to Dynamically Instantiate Classes in PHP without Using eval()?
Instantiating Classes through Dynamic Variables in PHP
Dynamically instantiating classes from variable names can be a valuable technique in PHP. Consider the following scenario:
$var = 'bar'; $bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
How can you achieve this without resorting to the much-debated eval() function, which you'd rather avoid?
Variable Assignment and Instantiation
The solution lies in creating a variable that holds the class name and then instantiating the class using the $ variable operator:
$classname = $var . 'Class'; $bar = new $classname("xyz");
This technique allows you to dynamically instantiate classes based on variable values, which can prove useful in patterns like the Factory pattern.
Further Considerations
To delve deeper into this topic, refer to PHP's documentation on Namespaces and dynamic language features, which provide more context and examples.
The above is the detailed content of How to Dynamically Instantiate Classes in PHP without Using eval()?. For more information, please follow other related articles on the PHP Chinese website!