Difference between DirectoryIterator and FileSystemIterator

BenMorel picture BenMorel · Sep 21, 2012 · Viewed 23.7k times · Source

PHP 5 introduced DirectoryIterator, and PHP 5.3 introduced FileSystemIterator.

FileSystemIterator extends DirectoryIterator, but the documentation fails to say what extra features it brings.

Can you tell the difference between DirectoryIterator and FileSystemIterator?

Answer

dbf picture dbf · Sep 21, 2012

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.