php-折叠时要求所有文件
有没有简单的方法要求文件夹中的所有文件?
never_had_a_name asked 2020-02-19T05:59:30Z
9个解决方案
49 votes
可能仅通过执行以下操作即可:
$files = glob($dir . '/*.php');
foreach ($files as $file) {
require($file);
}
使用opendir()和readdir()可能比glob()更有效。
Tom Haigh answered 2020-02-19T06:00:10Z
23 votes
做到这一点绝非易事,您需要在PHP中实现它。 这样的事情就足够了:
foreach (scandir(dirname(__FILE__)) as $filename) {
$path = dirname(__FILE__) . '/' . $filename;
if (is_file($path)) {
require $path;
}
}
soulmerge answered 2020-02-19T05:59:45Z
12 votes
没有简单的方法,就像在Apache中一样,在那里您只能输入.php,并且包含所有文件。
一种可能的方法是使用SPL中的RecursiveDirectoryIterator:
function includeDir($path) {
$dir = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($dir);
foreach ($iterator as $file) {
$fname = $file->getFilename();
if (preg_match('%\.php$%', $fname)) {
include($file->getPathname());
}
}
}
这将从$path中拉出所有.php结束文件,无论它们在结构中有多深。
K. Norbert answered 2020-02-19T06:00:39Z
9 votes
简单:
foreach(glob("path/to/my/dir/*.php") as $file){
require $file;
}
Tanner Ottinger answered 2020-02-19T06:00:58Z
3 votes
使用foreach回路。
foreach (glob("classes/*") as $filename) {
require $filename;
}
有关更多详细信息,请查看以下先前发布的问题:
Joshua Pinter answered 2020-02-19T06:01:23Z
1 votes
作为require_all()函数:
//require all php files from a folder
function require_all ($path) {
foreach (glob($path.'*.php') as $filename) require_once $filename;
}
Victor answered 2020-02-19T06:01:43Z
0 votes
递归地将所有文件列表和require_once放在一个目录中:
$files = array();
function require_once_dir($dir){
global $files;
$item = glob($dir);
foreach ($item as $filename) {
if(is_dir($filename)) {
require_once_dir($filename.'/'. "*");
}elseif(is_file($filename)){
$files[] = $filename;
}
}
}
$recursive_path = "path/to/dir";
require_once_dir($recursive_path. "/*");
for($f = 0; $f < count($files); $f++){
$file = $files[$f];
require_once($file);
}
Raju Rajotia Jangid answered 2020-02-19T06:02:03Z
0 votes
我要求所有同级的方式:
$files = glob(__DIR__ . '/*.php');
foreach ($files as $file) {
// prevents including file itself
if ($file != __FILE__) {
require($file);
}
}
userlond answered 2020-02-19T06:02:23Z
0 votes
解决方案使用opendir,readdir,closedir。 这也包括子目录。
function _require_all($path, $depth=0) {
$dirhandle = @opendir($path);
if ($dirhandle === false) return;
while (($file = readdir($dirhandle)) !== false) {
if ($file !== '.' && $file !== '..') {
$fullfile = $path . '/' . $file;
if (is_dir($fullfile)) {
_require_all($fullfile, $depth+1);
} else if (strlen($fullfile)>4 && substr($fullfile,-4) == '.php') {
require $fullfile;
}
}
}
closedir($dirhandle);
}
//Call like
_require_all(__DIR__ . '/../vendor/vlucas/phpdotenv/src');
Mirco Babin answered 2020-02-19T06:02:43Z