Home >Backend Development >PHP Tutorial >How Can I Instantiate a Class from a Variable in PHP?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 16:17:01501browse

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)

The above is the detailed content of How Can I Instantiate a Class from a Variable in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn