Php 包括来自具有foreach循环的文件夹的文件

Php 包括来自具有foreach循环的文件夹的文件,php,foreach,include,require,Php,Foreach,Include,Require,我使用下面的简单代码来包含公共文件夹中的所有文件 $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 fo

我使用下面的简单代码来包含公共文件夹中的所有文件

$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循环中包含所有其他文件,而不在上面写行?

您可以使用一种奇怪的解决方法来“移动”设置脚本:

$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; }

但这并不是很短。

您可以使用一种奇怪的解决方法来“移动”设置脚本:

$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; }
$files=glob($path['common'].$ds."*.php";
array_unshift($files,$path['common'].$ds."settings.php");
foreach ($files as $filename)
  require_once $filename;

但这并不是很短。

阅读php的自动加载功能。@N.B.为什么我需要在这里自动加载?另外,我想,自动加载类。你在路径前缀前加了两次。另外,使用目录分隔符通常是没有意义的,正斜杠适用于所有系统。@mario无意义?如何使用
内爆()
函数或类似的没有目录分隔符的函数?请阅读php的自动加载函数。@N.B.为什么我需要在这里自动加载?另外,我想,自动加载类。你在路径前缀前加了两次。另外,使用目录分隔符通常是没有意义的,正斜杠适用于所有系统。@mario无意义?如何使用
infrade()
函数或类似的没有目录分隔符的东西?@natural这只是因为这里的
array\u diff
技巧才需要的。另一种选择是一个
preg_grep
过滤器,只需像Eugen显示的那样预先添加一个条目即可。(下一种选择是重命名脚本,以便它们自动
sort()
按正确的顺序。例如,制作设置文件
!settings.php
00settings.php
,使其成为语义第一。--我对cron脚本使用类似的方法;认为
运行部件
)尽管我同意
数组映射到
包含
会很整洁,但它不会像它们那样工作(include、include_once、require、require_once等)是语言构造,因此不能作为回调函数访问。:@natural这只是由于这里的
array_diff
技巧而需要的。另一种选择是一个
preg_grep
过滤器,只需像Eugen显示的那样预先添加一个条目即可。(下一种选择是重命名脚本,以便它们自动
sort()
按正确的顺序。例如,制作设置文件
!settings.php
00settings.php
,使其成为语义第一。--我对cron脚本使用类似的方法;认为
运行部件
)尽管我同意
数组映射到
包含
会很整洁,但它不会像它们那样工作(include、include_once、require、require_once等)是语言构造,不能作为回调函数访问
$files=glob($path['common'].$ds."*.php";
array_unshift($files,$path['common'].$ds."settings.php");
foreach ($files as $filename)
  require_once $filename;