Including files from folder with foreach loop

无人久伴 提交于 2019-12-11 16:26:39

问题


I use following simple code to include all files from common folder.

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

As you see, at first I use

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

then including all the rest of files with foreach loop.

I wonder, if it is possible to include setting.php file first then all other files inside foreach loop, without writing line above?


回答1:


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



回答2:


You can use a quirky workaround to "move" the settings script up:

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

But that's not so much shorter really.



来源:https://stackoverflow.com/questions/8766982/including-files-from-folder-with-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!