Reputation: 3195
I'm looking for a way to load classes into PHP without using hardwired names.
The idea is the script will load a text file with names of 'components'(classes), then load them by the names in the file. For example:
<xml><Classes><class name="myClass"/></Classes></xml>
When the PHP is run, it would need to do something like this:
require_once {myClass}".class.php";
var myclass = new {myClass}();
Upvotes: 8
Views: 12750
Reputation: 77
Why not just use autoloader
spl_autoload_register(function ($class) {
require 'class_folder/' . $class . '.class.php';
});
Upvotes: 0
Reputation: 49
Use the ReflectionClass for this.
require_once $class . ".class.php";
$refl = new \ReflectionClass($class);
$params_for_construct = array($param1, param2);
$instance = $refl->newInstanceArgs($params_for_construct);
Upvotes: 0
Reputation: 458
Your example is almost correct as is. You can just replace {myClass} with $myClass and it should work.
Here's a simple example of how this could 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 output "myText" to the screen, the contents of your dynamically included class property.
Upvotes: 3
Reputation: 522091
require_once $class . ".class.php";
$myclass = new $class;
See http://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new.
Upvotes: 6