tags:

views:

3492

answers:

4

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.

A: 

I suggest you use a readdir() function and then loop and include the files (see the 1st example on that page).

Stiropor
A: 

If you are using php 5 you might want to use autoload instead.

SorinV
+16  A: 
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
Karsten
I thought there would be a cleaner looking way using include().But this will do just fine. Thanks everyone.
occhiso
I would build a proper module system with a configuration file, but that's just because I find that much more flexible than just including *everything*. :-)
staticsan
+4  A: 

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.'classses/',
    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;
     }
    }
}
Marius