2012-01-07 85 views
0

我使用以下简单代码来包含来自公用文件夹的所有文件。包含来自具有foreach循环的文件夹的文件

$path=array(); 
$ds=DIRECTORY_SEPARATOR; 
$path['root']=$_SERVER['DOCUMENT_ROOT']; 
$path['common']=$path['root'].$ds."common".$ds; 

//Include settings 
require $path['common'].$ds."settings.php"; 

//including common php files 
foreach (glob($path['common'].$ds."*.php") as $filename) { 
    if($filename!="settings.php") 
    require $path['common'].$ds.$filename; 
} 

正如你看到的,一开始我使用

require $path['common'].$ds."settings.php"; 

则包括文件的所有其余部分与foreach循环。

我想知道,如果有可能包括setting.php文件,然后所有其他文件在foreach循环内,而不写上面的行?

+0

了解php的自动加载功能。 – 2012-01-07 03:00:23

+0

@ N.B。为什么我需要在这里自动加载?另外,我认为,自动加载分类。 – 2012-01-07 03:01:08

+0

您正在预先考虑路径前缀两次。同样使用'DIRECTORY_SEPARATOR'通常毫无意义,正斜杠适用于所有系统。 – mario 2012-01-07 03:03:16

回答

3
$files=glob($path['common'].$ds."*.php"; 
array_unshift($files,$path['common'].$ds."settings.php"); 
foreach ($files as $filename) 
    require_once $filename; 
+0

+因为require_once真的是更简单的方法。 – mario 2012-01-07 03:12:22

2

您可以使用一个古怪的解决办法,以“移动”的设置脚本了:

$settings = array("$path[common]/settings.php"); 
$includes = glob("$path[common]/*.php"); 
$includes = array_merge($settings, array_diff($includes, $settings)); 

// load them all 
foreach ($includes as $i) { include $i; } 

但是,这不是这么多真的越短。

+0

+1 array_map() – 2012-01-07 03:07:46

+0

为什么$ settings是数组? – 2012-01-07 03:12:02

+0

@Tural这只是由于'array_diff'技巧在这里。另一种选择是'preg_grep'过滤器,并在Eugen显示的前面添加一个条目。 – mario 2012-01-07 03:14:04