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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.
    }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.