Home > Backend Development > PHP Tutorial > How to Dynamically Instantiate a PHP Class from a Variable?

How to Dynamically Instantiate a PHP Class from a Variable?

Mary-Kate Olsen
Release: 2024-11-23 11:13:04
Original
348 people have browsed it

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');
Copy after login

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;
    }
}
Copy after login

This factory class can be used as follows:

$instance = ClassFactory::create('barClass', ['argument for constructor']);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template