[英]How can I recursively include all files with a specific name in a folder using PHP?
假設我有一個名為parent
的文件夾,其中有許多子文件夾,例如child1
, child2
等。其中一些“子”文件夾中有一個名為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;
}
盡管包含所有文件聽起來很糟糕,但是可能:
$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讀取。 如果不能確保這一點,則必須為此編寫一個自定義遞歸函數(但這不太可能)。
同樣,您做的不是一個好的設計,並且會導致問題(比您想象的要早)。 如果您遵循OOP風格,則更好的方法是使用PHP的autload
機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.