2013-11-09 181 views
0

我想include我項目中每個目錄中的每個文件。我現在擁有的是,我include每個文件從一個特定的目錄在根目錄和所有子目錄中的Foreach文件

foreach (glob("*.php") as $filename) 
{ 
    include_once $filename; 
} 

但我也希望做每個目錄我已經和所有的文件一樣在那裏。我聽說過__autoload函數,但我有時也需要它用於非類函數。

回答

1

On this man page,第一評論給出遞歸列出所有文件的功能。只是適應它,以滿足您的需求:

<?php 
function include_all_php_files($dir) 
{ 
    $root = scandir($dir); 
    foreach($root as $value) 
    { 
     if($value === '.' || $value === '..') {continue;} 
     if(is_file("$dir/$value") && preg_match('#\.php$#', $value)) 
     { 
      include_once ("$dir/$value"); 
      continue; 
     } 
     include_all_php_files("$dir/$value"); 
    } 
} 
?> 
1

遞歸是你的朋友。

/** 
* @param string path to the root directory 
*/ 
function include_files($dir) { 
    foreach (glob($dir . "/*") as $file) { 
     if(is_dir($file)){ 
      include_files($file); 
     } else { 
      include_once($file); 
     } 
    } 
} 
+0

嘿。 include_files究竟做了什麼?因爲它告訴我未知的函數'include_files' – Musterknabe

+0

這是不可能的。但無論如何,如果你不瞭解遞歸,請使用@ jerska的答案。它開箱即用。礦井非常粗糙,因爲我認爲你可以根據你的需要調整想法。 –

+0

我的答案實際上也是一個遞歸函數。 – Jerska

0

試試這個。這對我有用。

相關問題