【发布时间】:2018-01-02 12:32:58
【问题描述】:
我正在尝试创建一个包含(通过 require_once)多个文件的脚本,但我期望它具有以下行为:
- 所需文件的所有文件名都定义为数组中的值
- 脚本检查数组中的所有文件是否存在于给定目录中
- 如果是,要求它们并继续(仅当它们都存在时)
- 如果否,终止脚本并显示错误消息(如果缺少任何文件)
更新
仔细查看我的原始脚本后,我发现它为什么不起作用。第二个 IF 语句 ($countMissing == 0) 在 FOR 循环内,它为找到的文件生成空数组。将 IF 语句从循环中取出来解决问题。
工作版本(稍作修改):
// Array with required file names
$files = array('some_file', 'other_file', 'another_file');
// Count how many files is in the array
$count = count($files);
// Eampty array for catching missing files
$missingFiles = array();
for ($i=0; $i < $count; $i++) {
// If filename is in the array and file exist in directory...
if (in_array($files[$i], $files) && file_exists(LIBRARIES . $files[$i] . '.php')) {
// ...update array value with full path to file
$files[$i] = LIBRARIES . $files[$i] . '.php';
} else {
// Add missing file(s) to array
$missingFiles[] = LIBRARIES . $files[$i] . '.php';
}
}
// Count errors
$countMissing = count($missingFiles);
// If there was no missing files...
if ($countMissing == 0) {
foreach ($files as $file) {
// ...include all files
require_once ($file);
}
} else {
// ...otherwise show error message with names of missing files
echo "File(s): " . implode(", ", $missingFiles) . " wasn't found.";
}
如果这个帖子不会被删除,我希望它对某人有所帮助。
【问题讨论】:
标签: php arrays if-statement include