2013-06-02 64 views
2

假設我有一個名爲parent 在那裏文件夾中,也有很多子像child1child2等 一些「孩子」的文件夾有一個文件叫他們module.php。 如何遞歸檢查parent文件夾的所有子文件夾,並在我的應用程序中包含名爲module.php的所有文件?我如何遞歸地使用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; 
} 
+0

http://php.net/manual/en/function.glob.php? – elclanrs

+0

@elclanrs AFAIK'glob'不能遞歸 – hek2mgl

+0

哦,你是對的,我的不好。迭代器應該在下面的問題中做。 – elclanrs

回答

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機制。

+0

如果你看看我原來的帖子,我更新了它,包括什麼樣的東西我正在努力。 :) – Aristeides

+0

但我的例子應該做的伎倆,不是嗎? (已測試過) – hek2mgl

+0

謝謝!是的,它的工作完美無瑕。 – Aristeides

相關問題