【问题标题】:How to include all php files from a directory?如何包含目录中的所有php文件?
【发布时间】:2021-04-18 14:28:39
【问题描述】:

我正在尝试使用此类代码从目录中包含 .php 文件。但它不起作用。谁能帮我?谢谢。

<?php
$dir = "/file/";
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while(($file = readdir($dh)) !== false) {
            if ($file != "." && $file != "..") {
               include "$file";
            }
        }
        closedir($dh);
    }
}
?>

【问题讨论】:

  • 为什么不用autoload
  • “不工作”是什么意思? 究竟是什么不起作用?您尝试过什么调试问题?
  • 当你说它不工作时,你是什么意思?从这里很难调试。值得检查的一件事是,对于/file/,开头的斜线通常意味着它将从服务器的根目录进行搜索。您可能想尝试使用类似./file/
  • $file 仅包含文件名,因此您必须在其前面加上 $dir,以便它可以从当前位置找到该子文件夹中的文件。 (假设“正常”include_path 配置设置。)
  • 尝试使用PHP Glob。还有Reading this Question

标签: php


【解决方案1】:

使用$dir 作为$file 的前缀后,它可以正常工作。

<?php
$dir = "../file/";
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file != "." && $file != "..") {
                include_once $dir . $file;
            }
        }
        closedir($dh);
    }
}
echo $a . "<br>" . $b;

?>

【讨论】:

    猜你喜欢
    • 2010-10-10
    • 2021-01-05
    • 1970-01-01
    • 2011-09-08
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多