How to include() all PHP files from a directory?


Question

Very quick n00b question, in PHP can I include a directory of scripts.

i.e. Instead of:

include('classes/Class1.php');
include('classes/Class2.php');

is there something like:

include('classes/*');

Couldn't seem to find a good way of including a collection of about 10 sub-classes for a particular class.

1
222
3/1/2009 11:53:58 AM

Accepted Answer

foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
417
3/1/2009 11:44:39 AM

Here is the way I include lots of classes from several folders in PHP 5. This will only work if you have classes though.

/*Directories that contain classes*/
$classesDir = array (
    ROOT_DIR.'classes/',
    ROOT_DIR.'firephp/',
    ROOT_DIR.'includes/'
);
function __autoload($class_name) {
    global $classesDir;
    foreach ($classesDir as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once ($directory . $class_name . '.php');
            return;
        }
    }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon