Search code examples
phpclassobjectauto-generate

php create objects from list of class files


I have directory CLASSES with files in my project.

../classes/class.system.php
../classes/class.database.php
...

I pull out every class and include it to main index.php with this code:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
}

and then I create (manually write) objects for example:

$system = new System();
$database = new Database();
...

Q: How can I automatically generate object for each class from list of files in directory CLASSES without writing them?

Thank you for your answers and code.

EDIT:

My working solution:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    $obj = strtolower($t[1]);
    $class = ucfirst($t[1]);
    ${$obj} = new $class();
}

Solution

  • // load classes and create objects
    foreach (glob("classes/class.*.php") as $filename) {
        require_once $filename;
        $t = explode(".",$filename);
        $obj = strtolower($t[1]);
        $class = ucfirst($t[1]);
        // create object for every class
        ${$obj} = new $class();
    }