In PHP, you may encounter a scenario where you need to instantiate a class from a variable's value. Let's illustrate this with an example:
$var = 'bar'; $bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
This method attempts to create an instance of the class specified by the $var variable. However, PHP does not support this syntax natively.
To achieve this without using eval(), you can utilize a variable to hold the class name:
$classname = $var . 'Class'; // e.g. $classname = 'barClass' $bar = new $classname('var for __construct()');
This technique is often employed in the Factory pattern, which is used to centralize class creation and decouple it from the creation process. In such scenarios, a factory class would create the desired class instances dynamically based on configuration or other parameters.
For more information on dynamic language features andnamespaces, refer to the following resources:
The above is the detailed content of How Can I Instantiate a Class from a Variable in PHP?. For more information, please follow other related articles on the PHP Chinese website!