"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Instantiate a Class from a Variable in PHP?

How Can I Instantiate a Class from a Variable in PHP?

Published on 2024-11-18
Browse:250

How Can I Instantiate a Class from a Variable in PHP?

Implementing Class Instantiation from a Variable in PHP

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.

Alternative Approach without eval()

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()');

Factory Pattern

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.

Further Resources

For more information on dynamic language features andnamespaces, refer to the following resources:

  • [Namespaces](https://www.php.net/manual/en/language.namespaces.php)
  • [Dynamic Language Features](https://www.php.net/manual/en/language.types.dynamic.php)
Latest tutorial More>

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