In PHP, the ability to instantiate a class from a variable can be useful in various scenarios. One can achieve this functionality with approaches beyond the controversial eval() method.
Problem:
Consider the following code:
$var = 'bar'; $bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
This code aims to instantiate a class using a variable as the class name. However, the syntax is incorrect.
Solution:
To achieve dynamic class instantiation without eval(), one can store the class name in a variable first:
$classname = $var.'Class'; $bar = new $classname("xyz");
In this approach, the class name is assigned to a variable ($classname), and then the new instance of that class is created using the $classname variable.
Usage:
This technique is commonly employed within the Factory pattern, which allows for the creation of objects without specifying the exact class name. It also finds applications in dependency injection frameworks, where class names can be dynamically generated or configured at runtime.
For further understanding, refer to the documentation on Namespaces and dynamic language features in PHP.
以上是如何在 PHP 中不使用 eval() 實作動態類別實例化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!