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.
An easy way : a simple function using `RecursiveDirectoryIterator` instead of `glob()`.

```
function include_dir_r( $dir_path ) {
    $path = realpath( $dir_path );
    $objects = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( $path ), \RecursiveIteratorIterator::SELF_FIRST );
    foreach( $objects as $name => $object ) {
        if( $object->getFilename() !== "." && $object->getFilename() !== ".." ) {
            if( !is_dir( $name ) ){
                include_once $name;
            }
        }
    }
}

```