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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题