Re: RecursiveDirectoryIterator and foreach

From: Date: Mon, 23 Feb 2009 17:25:11 +0000
Subject: Re: RecursiveDirectoryIterator and foreach
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-288688@lists.php.net to get a copy of this message
Ryan Panning wrote:
I have discovered that when I foreach over a RecursiveDirectoryIterator (see example below) the $item actually turns into a SplFileInfo object. I would expect it to be a RecursiveDirectoryIterator. How do I do a hasChildren() on SplFileInfo? However, if I change it to a non-recursive, DirectoryIterator, $item is what I would expect, DirectoryIterator. I've tested this with 5.2.8 and 5.3b1. I'm guessing this is an issue with my setup as I'm sure I've gotten this to work before... $dir = new RecursiveDirectoryIterator('/path/to/dir'); foreach ($dir as $item) {
    print get_class($item) . "\r\n";
}
Alright, I've found a related PHP bug report. http://bugs.php.net/bug.php?id=44018 It seems that the default behavior is to return a SplFileInfo object. However, if 0 is passed as a flag then a RecursiveDirectoryIterator should be returned. However, I cannot seem to get that to work with 5.2.8. Testing previous versions, this option no longer works as of 5.2.6, but did in 5.2.5. This seems like a bug to me, however that bug was marked as "Wont Fix". The default behavior should be RecursiveDirectoryIterator as there is a flag for CURRENT_AS_FILEINFO. Any thoughts on that? @ Marcus, what was the reasoning not to fix this? And why did it break in 5.2.6? In relation, I've found a workaround, use while(). That way I'm always working off of the $dir. I'd rather use foreach though.. $dir = new RecursiveDirectoryIterator('/path/to/dir'); while ($dir->valid()) {
    print get_class($dir) . "\r\n";
    $dir->next();
}

« previous php.general (#288688) next »