Jump to content

Looping through a directory calling and requiring classes


scrubbicus

Recommended Posts

I'm trying to find an easy way to loop through my classes directory and require_once, then assign them a variable through a loop.

 

What I have is:

 

$dir = "assets/classes/";

$classes = array();

$handle = opendir ( $dir );

 

// LOAD ALL COMPONENTS

while ( FALSE !== ( $file = readdir ( $handle ) ) )

{

if ( $file != "." && $file != ".." )

{

$classes[] = $file;

}

}

 

closedir( $handle );

 

var_dump($classes);

 

foreach( $classes as $class )

{

require_once($dir . $class);

${$class} = new $class;

}

 

It's not working :(

 

Any help is appreciated, thanks.

Eww, this doesn't look good.

 

Its not working because your files have an extension (presumably .php), your classes would then need to be named foo.php for instance. This is obviously not valid.

 

You'll need to remove the .php at least.

 

Ever heard of __autoload though? It'll likely help you out.

Don't include each and every class. It's possible you don't need the half of 'em at that time. I don't encourage the use of __autoload() as spl_autoload_* functions allow for more flexibility and allows to register multiple autoload functions to load classes from multiple resources.

 

spl_autoload_extensions('.php,.php5,.php4');//allows to run 4, 5 & 6 alongside. In the event a filename is found for .php, .php5 and .php4 then only .php is included.

// Initializes the autoload queue (FIFO)
spl_autoload_register('autoloadLibraryClass');
//spl_autoload_register();//uses default implementation of spl_autoload()

function autoloadLibraryClass($className) {
    global $libraryDirectory;
    $extensions = explode(',', spl_autoload_extensions());
    foreach ($extensions as $extension) {
        $extension = trim($extension);
        $fullPath = implode(DIRECTORY_SEPARATOR, array($libraryDirectory, $className . $extension));
        if (file_exists($fullPath)) {
            require_once($fullPath);
        }
    }
    if (!class_exists($className)) {
        //class still not loaded.
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.