请留意下面例子中检查 readdir()
返回值的风格。这里明确地测试返回值是否全等于(值和类型都相同――更多信息参见比较运算符)FALSE
,否则任何目录项的名称求值为
FALSE
的都会导致循环停止(例如一个目录名为“0”)。
<?php
// 注意在 4.0.0-RC2 之前不存在 !== 运算符
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
/* 这是正确地遍历目录方法 */
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
/* 这是错误地遍历目录的方法 */
while ($file = readdir($handle)) {
echo "$file\n";
}
closedir($handle);
}
?>