我在PHP if
语句中使用变量作为目录名时遇到了问题:
if (($handle = opendir("news"))) {
// Read all file from the actual directory
while ($file = readdir($handle)) {
if (!is_dir($file)) {
$fileList[] = $file;
}
}
}
当我使用变量($newsDir
)而不是字符串字面值作为目录名("news"
)时,脚本停止工作。
$newsDir = $_SERVER[DOCUMENT_ROOT] . "edit/news";
var_dump(file_exists($newsDir));
// bool(true)
var_dump(is_dir($newsDir));
// bool(true)
var_dump($newsDir);
// string(36) "/f5/jb-cms-testing/public//edit/news"
if (($handle = opendir($newsDir))) {
// Read all file from the actual directory
while ($file = readdir($handle)) {
if (!is_dir($file)) {
$fileList[] = $file;
}
}
}
它不会抛出任何错误,函数只是不能正常运行。起初,我认为这是因为我的$newsDir
变量是$_SERVER[DOCUMENT_ROOT] . "edit/news"
,但即使我将$newsDir
设置为"news"
,它也不起作用。因此,据我所知,这与我正在使用一个变量有关。
知道为什么吗?此外,这是唯一的地方,唯一的文件,$handle
发生,所以我不知道为什么它在所有的工作。这是一段时间前,我建立了这个,我使用的是一个教程,所以我不确定它到底是如何工作的。它基本上只是对news
目录中的文件进行排序的一种方法。
使用以下命令检查错误在哪里(例如来自php.net)
<?php
// Report all PHP errors
error_reporting(-1);
$dir = $_SERVER[DOCUMENT_ROOT] . "edit/news";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
$fileList[] = $file;
echo "filename: $file : filetype: " . filetype($dir . $file) . "read 'n";
}
closedir($dh);
}
}
?>
哇。我想明白了。只是你显然不能在函数外使用变量。我将vars.php文件包含在函数之外,这导致了错误。我不知道你为什么做不到,也许有人能给我开导一下?