2013-11-09 186 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

试试这个。这对我有用。

相关问题