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

Viewed 264216

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.

15 Answers
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}

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

this is just a modification of Karsten's code

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}

include_all_php("my_classes");
<?php
//Loading all php files into of functions/ folder 

$folder =   "./functions/"; 
$files = glob($folder."*.php"); // return array files

 foreach($files as $phpFile){   
     require_once("$phpFile"); 
}

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

Try using a library for that purpose.

That is a simple implementation for the same idea I have build. It include the specified directory and subdirectories files.

IncludeAll

Install it via terminal [cmd]

composer install php_modules/include-all

Or set it as a dependency in the package.json file

{
  "require": {
    "php_modules/include-all": "^1.0.5"
  }
}

Using

$includeAll = requires ('include-all');

$includeAll->includeAll ('./path/to/directory');

This is a late answer which refers to PHP > 7.2 up to PHP 8.

The OP does not ask about classes in the title, but from his wording we can read that he wants to include classes. (btw. this method also works with namespaces).

By using require_once you kill three mosquitoes with one towel.

  • first, you get a meaningful punch in the form of an error message in your logfile if the file doesn't exist. which is very useful when debugging.( include would just generate a warning that might not be that detailed)
  • you include only files that contain classes
  • you avoid loading a class twice
spl_autoload_register( function ($class_name) {
    require_once  '/var/www/homepage/classes/' . $class_name . '.class.php';
} );

this will work with classes

new class_name;

or namespaces. e.g. ...

use homepage\classes\class_name;

Answer ported over from another question. Includes additional info on the limits of using a helper function, along with a helper function for loading all variables in included files.

There is no native "include all from folder" in PHP. However, it's not very complicated to accomplish. You can glob the path for .php files and include the files in a loop:

foreach (glob("test/*.php") as $file) {
    include_once $file;
}

In this answer, I'm using include_once for including the files. Please feel free to change that to include, require or require_once as necessary.

You can turn this into a simple helper function:

function import_folder(string $dirname) {
    foreach (glob("{$dirname}/*.php") as $file) {
        include_once $file;
    }
}

If your files define classes, functions, constants etc. that are scope-independent, this will work as expected. However, if your file has variables, you have to "collect" them with get_defined_vars() and return them from the function. Otherwise, they'd be "lost" into the function scope, instead of being imported into the original scope.

If you need to import variables from files included within a function, you can:

function load_vars(string $path): array {
    include_once $path;
    unset($path);
    return get_defined_vars();
}

This function, which you can combine with the import_folder, will return an array with all variables defined in the included file. If you want to load variables from multiple files, you can:

function import_folder_vars(string $dirname): array {
    $vars = [];
    foreach (glob("{$dirname}/*.php") as $file) {

        // If you want to combine them into one array:
        $vars = array_merge($vars, load_vars($file)); 

        // If you want to group them by file:
        // $vars[$file] = load_vars($file);
    }
    return $vars;
}

The above would, depending on your preference (comment/uncomment as necessary), return all variables defined in included files as a single array, or grouped by the files they were defined in.

On a final note: If all you need to do is load classes, it's a good idea to instead have them autoloaded on demand using spl_autoload_register. Using an autoloader assumes that you have structured your filesystem and named your classes and namespaces consistently.

Related