April 24, 2012

php create objects from list of class files

Question by ing. Michal Hudak

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();
}

Answer by ing. Michal Hudak

// 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();
}

Answer by Starx

IF you follow a typical pattern, while creating those files like

class.<classname>.php

Then

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

}
...

Please fill the form - I will response as fast as I can!