Loading PHP classes from a string

I am looking for a way to load classes in PHP without using hard names.

The idea behind the script is to load a text file with the names of the โ€œcomponentsโ€ (classes), and then load them by the names in the file. For example:

<xml><Classes><class name="myClass"/></Classes></xml> 

When PHP starts up, it will need to do something like this:

 require_once {myClass}".class.php"; var myclass = new {myClass}(); 
+7
source share
4 answers
 require_once $class . ".class.php"; $myclass = new $class; 

See http://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new .

+5
source

Your example is almost right as it is. You can just replace myClass with $ myClass and it should work.

Here is a simple example of how this can be used:

 File: myClass.class.php <?php class myClass { public $myVar = 'myText'; } ?> File: test.php <?php $className = "myClass"; require_once $className . ".class.php"; $myInstance = new $className; echo $myInstance->myVar; ?> 

This should display "myText" on the screen, the contents of your dynamically included class property.

+3
source

Use ReflectionClass for this.

 require_once $class . ".class.php"; $refl = new \ReflectionClass($class); $params_for_construct = array($param1, param2); $instance = $refl->newInstanceArgs($params_for_construct); 
0
source

Why not just use the autoloader

 spl_autoload_register(function ($class) { require 'class_folder/' . $class . '.class.php'; }); 
0
source

All Articles