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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3