问题
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