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: 
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.
```

$dir = new RecursiveDirectoryIterator('change this to your custom root directory');
foreach (new RecursiveIteratorIterator($dir) as $file) {
    if (!is_dir($file)) {
        if( fnmatch('*.php', $file) ) // you can change the file extension to any that you require.
        /* do anything here */
    }
}

```