简体   繁体   English

如何使用PHP递归地将所有具有特定名称的文件包含在文件夹中?

[英]How can I recursively include all files with a specific name in a folder using 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 . 假设我有一个名为parent的文件夹,其中有许多子文件夹,例如child1child2等。其中一些“子”文件夹中有一个名为module.php的文件。 How can I recursively check all subfolders of the parent folder and include all files named module.php in my application? 如何递归检查parent文件夹的所有子文件夹,并在应用程序中包含所有名为module.php文件?

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();
}

Btw, this example is derived from a comment in the PHP manual . 顺便说一句,此示例来自PHP手册中注释 To make it working, make sure that all sub folders are readable by PHP in that folder. 为使其正常工作,请确保该文件夹中的所有子文件夹均可被PHP读取。 If cannot make this sure you will have to write a custom recursive function for that (but this is unlikely). 如果不能确保这一点,则必须为此编写一个自定义递归函数(但这不太可能)。

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. 如果您遵循OOP风格,则更好的方法是使用PHP的autload机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM