【问题标题】:Including files from folder with foreach loop使用 foreach 循环包含文件夹中的文件
【发布时间】:2012-02-04 17:20:16
【问题描述】:

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

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

【问题讨论】:

  • 了解php的自动加载功能。
  • @N.B.为什么我需要在这里自动加载?另外,我认为自动加载类。
  • 您将路径前缀添加两次。同样使用DIRECTORY_SEPARATOR 通常是没有意义的,正斜杠适用于所有系统。
  • @mario 毫无意义?如何在没有 DIRECTORY_SEPARATOR 的情况下使用implode() 函数或类似的东西?

标签: php foreach include require


【解决方案1】:
$files=glob($path['common'].$ds."*.php";
array_unshift($files,$path['common'].$ds."settings.php");
foreach ($files as $filename)
  require_once $filename;

【讨论】:

    【解决方案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; }
    

    但这并没有那么短。

    【讨论】:

    • @Tural 这只是因为array_diff 这里的技巧才需要。另一种选择是preg_grep 过滤器,并且只是像 Eugen 所示的那样添加一个条目。
    • (下一个替代方案是重命名脚本,以便它们以正确的顺序自动sort()。例如,将设置文件设置为!settings.php00settings.php,使其在语义上成为第一。- - 我正在为 cron 脚本使用类似的东西;想想run-parts。)
    • 尽管我同意 array_mapinclude 会很整洁,但它不会起作用,因为它们(包括、include_once、require、require_once 等)是语言结构,因此无法访问回调函数。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2017-06-21
    • 2012-08-23
    相关资源
    最近更新 更多