Question: I would like to automatically `include/require` all `.php` files under all directories. For example:

(Directory structure)

```
-[ classes
    --[ loader (directory)
        ---[ plugin.class.php
    --[ main.class.php
    --[ database.class.php

```

I need a function that automatically loads all files that end in `.php`

I have tried all-sorts:

```
$scan = scandir('classes/');
foreach ($scan as $class) {
    if (strpos($class, '.class.php') !== false) {
        include($scan . $class);
    }
}

```

Answer: 
Well, if you want to include all php files with a certain ending even in subdirectories, you have to make a recursive function. Something like this:

```
function load_classphp($directory) {
    if(is_dir($directory)) {
        $scan = scandir($directory);
        unset($scan[0], $scan[1]); //unset . and ..
        foreach($scan as $file) {
            if(is_dir($directory."/".$file)) {
                load_classphp($directory."/".$file);
            } else {
                if(strpos($file, '.class.php') !== false) {
                    include_once($directory."/".$file);
                }
            }
        }
    }
}

load_classphp('./classes');

```
This is probably the simplest way to recursively find patterned files:

```
$dir = new RecursiveDirectoryIterator('classes/');
$iter = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($iter, '/^.+\.class\.php$/', RecursiveRegexIterator::GET_MATCH); // an Iterator, not an array

foreach ( $files as $file ) {
  include $file; // $file includes `classes/`
}

```

`RecursiveDirectoryIterator` is a tricky beast, so learning all about it is probably not doable. The interwebs has many specific examples though. The trick is to search for it.