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

时间:2013-06-02 21:44:08

标签: php recursion include

假设我有一个名为parent的文件夹 在那里,有许多子文件夹,如child1child2等。 其中一些“子”文件夹中有一个名为module.php的文件。 如何递归检查parent文件夹的所有子文件夹,并在我的应用程序中包含名为module.php的所有文件?

我尝试了下面的内容并且无法弄清楚出了什么问题:

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

1 个答案:

答案 0 :(得分:4)

虽然包含所有文件的设计听起来不错,但有可能:

$directory = new RecursiveDirectoryIterator('path/to/project/');
$recIterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($recIterator, '/\/module.php$/i');

foreach($regex as $item) {
    include $item->getPathname();
}

顺便说一下,这个例子来自comment in the PHP manual。要使其正常工作,请确保该文件夹中的PHP可以读取所有子文件夹。如果不能确定你必须为此编写自定义递归函数(但这不太可能)。

同样,你所做的不是一个好的设计,会导致问题(比你想象的更早)。如果您遵循OOP样式,更好的方法是使用PHP的autload机制。