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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题