The explanation of Rubens Ribeiro, author of blog PHP is very good:
Directoryiterator
The class DirectoryIterator
implements the interface Iterator
, she
has the methods to manipulate the "pointer" for the driven item.
For example, it has the method rewind
to return to the first
position. Also, how implements the interface SeekableIterator
,
has the method seek
, which moves the pointer to a desired position.
Filesystemiterator
The class FilesystemIterator
that extends the class
DirectoryIterator
, and offers additional resources. For example,
inform binary flags to get some behaviors, such as:
- Ignore the "." and ".."
- Follow symbolic links
- Specify the type of return of the method
current
(used in iterations with foreach
), etc..
Globiterator
Although it is not in your question, I find it interesting to say that there is also the class GlobIterator
.
The class GlobIterator
extends the class FilesystemIterator
and
offers the additional feature of scrolling through items from a
expression, as shown with the glob function. However, by some
unknown reason, the iterator does not have a similar behavior
to that proposed by the option GLOB_BRACE
.
Recommendation for use
The use of these classes is recommended as they offer the same features as opendir
, readdir
and closedir
(and some new), and is aligned with the Object-Oriented model, where the resources of the PHP
has walked. The only drawback is the incompatibility with old versions of PHP
(lower than version 5).
Difference
DirectoryIterator
is an extension of SplFileInfo
and the FilesystemIterator
is an extension of DirectoryIterator
. And the two implement Iterator
, Traversable
, SeekableIterator
.
Example DirectoryIterator
:
$it = new DirectoryIterator(__DIR__);
foreach ($it as $fileinfo) {
if (!$fileinfo->isDot())
var_dump($fileinfo->getFilename());
}
Example FilesystemIterator
:
$it = new FilesystemIterator(__DIR__);
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
I removed the examples from that reply stackoverflow.
Read the full article on: Browse Directories and Files with PHP.
Something tells me that, for once, they are conceptually wrong, at least in the nomenclature :D
– Maniero
@bigown why would they be "conceptually wrong"? which one is wrong?
– Wallace Maxters
I just wrote "something tells me" :P But if directory is something that is part of a filing system, this heritage is weird... But I’m not saying it’s all wrong there, nor would I be able to say without understanding.
– Maniero