PHP递归文件加载器

I have been racking my head trying to figure out why this simple function is not working, and I figured it's time to see if anyone else can find what I'm missing. The function is a fairly simple snippet of code that will search recursively through a directory, it's children, and it's children's children and so on and load in PHP files that are required for the application to run.

As always, any guidance and assistance is appreciated. Thanks.

Code

global $_MWC;
$_MWC = array();    // Create blank array to overwrite previously used data.
$_MWC['base'] = dirname(__FILE__);    // Equal to "/base"

// Create a function that will recursively load PHP files needed to run application.
function require_all_functions($dir) {
    global $_MWC;
    $scan = glob($_MWC['base'] . '/' . $dir . '/*');
    foreach ($scan as $path) {
        if (preg_match('/\.php$/', $path)) {
            require_once $path;
        }elseif (is_dir($path)){
            require_all_functions($path);
        }
    }
}

// Lets load all files in the addons directory for use in the system.
require_all_functions('addons');

print_r(get_included_files());    // FOR TESTING ONLY

Output

Array ( [0] => /base/addons/a.php )

File Structure

/base/addons/a.php
/base/addons/sub1/b.php
/base/addons/sub1/sub2/c.php

Here's the step to achieve this

  1. Get file in current directory put them into an array
  2. Get folder in current directory
  3. Loop through them
  4. Call the function itself on each directory
  5. Append result to $files array
  6. After all folder and subfolder been reached return $files

Example :

function glob_recursive($pattern)
{
    $files = glob($pattern, $flags);

    foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern)));
    }

    return $files;
}

$phpFiles = glob_recursive($_MWC['base'] . '/' . $dir . '/*.php');

foreach($phpFiles as $phpFile){
     require_once $phpFile;
}

When you do this:

$_MWC = dirname(__FILE__);

$_MWC['base'] does not exist, dirname return a string : $_MWC . '/' . $dir...

Set error_reporting to -1 to see those kind of errors.

Or, you could use iterators to have a slightly nicer to read code:

    $d = new RecursiveDirectoryIterator(dirname(__FILE__));
    $Iterator = new RecursiveIteratorIterator($d);
    $php_files = new RegexIterator($Iterator, '/\.php$/', RecursiveRegexIterator::GET_MATCH);
    iterator_apply($php_files,"require_once");