Home >Backend Development >PHP Tutorial >How to Dynamically Instantiate a Class in PHP Without Using `eval()`?
Understanding Dynamic Class Instantiation in PHP
In PHP, it is possible to dynamically instantiate a class from a variable. However, this approach can be confusing and is generally discouraged for security reasons. Let's delve into a safer method that avoids the use of eval().
As an example, the task at hand is to instantiate the barClass with the variable $var containing its name ('bar').
To achieve this without eval(), follow these steps:
Assign the class name to a variable:
$classname = $var . 'Class'; // e.g., $classname = 'barClass'
Instantiate the class with the variable:
$bar = new $classname("xyz");
This method replaces the variable $bar with an instance of the barClass.
It's worth noting that this technique is commonly employed within the Factory design pattern. By creating a factory class that generates specific classes based on supplied parameters, you can dynamically instantiate objects without the need for direct class references.
For further insights into PHP's dynamic language features, refer to "Namespaces and dynamic language features."
The above is the detailed content of How to Dynamically Instantiate a Class in PHP Without Using `eval()`?. For more information, please follow other related articles on the PHP Chinese website!