16
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".")) as $file) {
  echo "$file\n";
}

每当我尝试列出的目录中有不可读的子目录时,此代码是否有任何方法不抛出 UnexpectedValueException“无法打开目录:权限被拒绝”?

更新

转换foreach()while()并显式调用Iterator::next()Wrapped intry() catch {} 无济于事。这段代码:

$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
while($iter->valid()) {
    $file = $iter->current();
    echo "$file\n";
    try {
        $iter->next();
    } catch(UnexpectedValueException $e) {
    }
};

如果存在不可读的子目录,则为无限循环。

4

2 回答 2

24

显然你可以将$flags参数传递给构造函数。docs 中只有一个标志,但它完全符合您的要求:catches exceptions during getChildren() calls and simply jumps to the next element.

将您的课程创建代码更改为

new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("."), 
    RecursiveIteratorIterator::LEAVES_ONLY,
    RecursiveIteratorIterator::CATCH_GET_CHILD);

它应该可以工作

于 2010-12-28T22:30:01.933 回答
8

你可以做这样的事情:

class ReadableFilter extends RecursiveFilterIterator{
    public function accept(){
            return $this->current()->isReadable();
    }
}

$filteredIterator = new RecursiveIteratorIterator(new ReadableFilter(new RecursiveDirectoryIterator(".")));

foreach ($filteredIterator as $file){
    echo "$file\n";
}
于 2010-12-28T18:28:34.123 回答