我一直在绞尽脑汁想弄清楚为什么这个简单的功能不起作用,我想是时候看看是否还有其他人能找到我所缺少的东西。该函数是一个相当简单的代码片段,它将递归地搜索一个目录,它是子目录,它是子目录的子目录等等,并加载应用程序运行所需的 PHP 文件。
一如既往,我们将不胜感激任何指导和帮助。谢谢。
代码
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
输出
Array ( [0] => /base/addons/a.php )
文件结构
/base/addons/a.php
/base/addons/sub1/b.php
/base/addons/sub1/sub2/c.php
最佳答案
这是实现这一目标的步骤
- 获取当前目录中的文件并将它们放入数组中
- 获取当前目录下的文件夹
- 遍历它们
- 在每个目录上调用函数本身
- 将结果附加到 $files 数组
- 到达所有文件夹和子文件夹后返回 $files
示例:
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;
}
关于PHP递归文件加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29108971/