Home >Backend Development >PHP Tutorial >How to Dynamically Instantiate a PHP Class from a Variable?
Instantiating a PHP Class Dynamically from a Variable
In PHP, it is possible to instantiate a class dynamically using a string variable containing the class name. This can be achieved by first assigning the class name to a new variable, and then using the dollar sign ($) operator to instantiate the class.
Example:
$var = 'bar'; $classname = $var . 'Class'; $bar = new $classname('argument for constructor');
This will create a new instance of the barClass class, passing in the argument 'argument for constructor' to its constructor.
Using a Factory Pattern:
This technique is often used in the context of the Factory pattern, where a factory class is responsible for creating and returning instances of different classes based on a given parameter. For example:
class ClassFactory { public static function create($className, $args = []) { $instance = new $className(...$args); return $instance; } }
This factory class can be used as follows:
$instance = ClassFactory::create('barClass', ['argument for constructor']);
Additional Notes:
When using this technique, it is important to ensure that the variable containing the class name is properly sanitized to prevent arbitrary class instantiation. This can be achieved using functions like preg_replace() to validate the class name.
The above is the detailed content of How to Dynamically Instantiate a PHP Class from a Variable?. For more information, please follow other related articles on the PHP Chinese website!