php 如何引入整个文件夹内的 .php?

现在一般我引入就是这样

require_once '/configurations/environment.php';

只是这样当 configurations 多了很多个 php 时,就必须一个一个打上去引入

require_once '/configurations/environment.php';
require_once '/configurations/environment2.php';
require_once '/configurations/environment3.php';
require_once '/configurations/environment4.php';
require_once '/configurations/environment5.php';
.....

这样是否太麻烦
有无我只要引入「configurations」文件夹,等同于引入了里面全部的 .php 程式呢?

阅读 7.7k
5 个回答
function requireDir($dir){
    $handle = opendir($dir);
    while(false !== ($file = readdir($handle))){
        if($file != '.' && $file != '..'){
            $filepath = $dir.'/'.$file;
            if(filetype($filepath) == 'dir'){
                requireDir($filepath);
            }else{
                require_once $filepath;
            }
        }
    }
}
requireDir('./php_fun');
test();

自己写个方法就行了,不过最好还是加上命名空间。不说可以解决方法名冲突,还能让自己看起来很专业哈哈哈

尽量避免使用 *_once 方法。


$files = glob('/path/*.php');
foreach($files as $file){
    require $file;
}

如果引入的文件都不是类文件且可以确定文件个数不变的,可以配置composer

"autoload": {
    "files": [
        "configurations/environment.php",
        "configurations/environment1.php",
        ...
    ]
},

如果文件个数经常变或者文件名经常变的话,还是参考其他几位答主的回答吧

原答案:
php的include和require函数只能引入文件,不能引入文件夹,也没有引入文件夹的相关函数。
可以了解一下php的命名空间和自动加载。
https://blog.csdn.net/xcqingf...

自动加载了解下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题