Difference between DirectoryIterator and FileSystemIterator

Solution 1:

This goes out of the top of my head, where I sort of got caught in the changes prior to PHP 5.3 that were going to change in 5.3 and later, concerning the SPL (StandardPHPLibrary) and stuff that were going to be moved to the (horrible) PECL extensions.

The major thing that changed since 5.3, was that the SPL became an extension that could not be disabled anymore, see the changelog of 5.3 noting that

  • Added SPL to list of standard extensions that cannot be disabled. (Marcus)

so all the fancy classes like DirectoryIterator or SPLDoublyLinkedList were now a fix suite of classes that came with PHP 5.3.

There were a lot of discussions going on that the DirectoryIterator was still very clumsy in iterating over files/directories and from behaviour not anonymous enough to the filesystem being used. Because depending on the filesystem (Windows NTFS / *nix EXTx) the results the iterator would return were different from another, where *nix environments per default always resulted the dot and double dot directories (. and ..) as valid directories. These dot directories could then be filtered in the loop by using the isDot() method.

$it = new DirectoryIterator(__DIR__);
foreach ($it as $fileinfo) {
  if (!$fileinfo->isDot())
    var_dump($fileinfo->getFilename());
}

So FilesystemIterator became the new parent class in PHP 5.3, which prior to its release was the DirectoryIterator (where FilesystemIterator extends DirectoryIterator to implement this interchangeable behaviour by default). The behaviour, or result the FilesystemIterator produced, would then be equal to all different filesystems and interchangeable without the need of any overhead in the loop

$it = new FilesystemIterator(__DIR__);
foreach ($it as $fileinfo) {
  echo $fileinfo->getFilename() . "\n";
}

It's a good question why they didn't update the documentation for noticing the user on the fact that actually the FilesystemIterator preceded the DirectoryIterator.

Solution 2:

DirectoryIterator is an extension of SplFileInfo

while

FilesystemIterator is an extension of DirectoryIterator

and the both implements

Iterator , Traversable , SeekableIterator

FilesystemIterator has flags which affects its behaviors when working which files which can be very useful such as FOLLOW_SYMLINKS , SKIP_DOTS etc and this makes most of its difference.

You can see full flags at FilesystemIterator predefined constants

Example

$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ( $iterator as $fileinfo ) {
    var_dump($fileinfo->current()); // would return object(DirectoryIterator)
}

Example 2

$iterator = new FilesystemIterator(__DIR__, FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ( $iterator as $fileinfo ) {
    var_dump($iterator->current()) . "\n"; // Would return full path eg /www/examples/example.php
}