如何使用PHP以递归方式将包含特定名称的所有文件包含在文件夹中? [英] How can I recursively include all files with a specific name in a folder using PHP?
问题描述
假设我有一个名为 parent的文件夹
在那里,有许多子文件夹,如 child1
, child2
等。
其中一些子文件夹中有一个名为 module.php
的文件。
如何递归检查 parent
文件夹的所有子文件夹,并包含名为 module.php
的所有文件我的申请?
Suppose I have a folder named parent
In there, there are many subfolders like child1
, child2
etc.
Some of these "child" folders have a file in them called module.php
.
How can I recursively check all subfolders of the parent
folder and include all files named module.php
in my application?
我尝试了以下内容并且无法弄清楚出了什么问题:
I tried the below and can't figure out what's wrong:
if ( !function_exists( 'glob_recursive' ) ) {
function glob_recursive( $pattern, $flags = 0 ) {
$files = glob( $pattern, $flags );
foreach ( glob( dirname( $pattern ) . '/*', GLOB_ONLYDIR|GLOB_NOSORT ) as $dir ) {
$files = array_merge( $files, glob_recursive( $dir . '/' . basename( $pattern ), $flags ) );
}
return $files;
}
}
foreach ( glob_recursive( locate_template('/lib/modules/*/module.php' ) as $module ) {
require_once $module;
}
推荐答案
虽然听起来很糟糕设计包括所有文件,有可能:
Although it sounds like a bad design to include all files, it is possible:
$directory = new RecursiveDirectoryIterator('path/to/project/');
$recIterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($recIterator, '/\/module.php$/i');
foreach($regex as $item) {
include $item->getPathname();
}
顺便说一句,这个例子来源于评论PHP手册。为了使它工作,请确保PHP在该文件夹中可以读取所有子文件夹。如果无法确保您必须为此编写自定义递归函数(但是这个我不太可能)。
Btw, this example is derived from a comment in the PHP manual. To make it working, make sure that all sub folders are readable by PHP in that folder. If cannot make this sure you will have to write a custom recursive function for that (but this is unlikely).
同样,你所做的不是一个好的设计,会导致问题(比你想象的更早)。如果您遵循OOP风格,更好的方法是使用 <$ c PHP的$ c> autload 机制。
Again, what you are doing is not a good design and will lead to problems (earlier than you might think). If you are following the OOP style, a better approach would be to use the autload
mechanism of PHP.
这篇关于如何使用PHP以递归方式将包含特定名称的所有文件包含在文件夹中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!