dongyo7931 2015-03-17 20:21
浏览 63
已采纳

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
  • 写回答

3条回答 默认 最新

  • dourang20110122 2015-03-17 20:31
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动