php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #75135 Elements of DirectoryIterator is the iterator itself
Submitted: 2017-08-29 17:38 UTC Modified: 2021-05-12 13:15 UTC
From: morozov at tut dot by Assigned:
Status: Open Package: SPL related
PHP Version: 7.1.8 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: morozov at tut dot by
New email:
PHP Version: OS:

 

 [2017-08-29 17:38 UTC] morozov at tut dot by
Description:
------------
When iterating over a DirectoryIterator, each element is the iterator itself representing the current file. It makes it impossible to convert the iterator to array, as all its elements will be references to the same object (the iterator).

See https://3v4l.org/P0H06.

Test script:
---------------
$it = new DirectoryIterator('/tmp');
$array = iterator_to_array($it);

foreach ($array as $fileInfo) {
    var_dump($fileInfo->getRealPath());
}

/*

Outputs:

bool(false)
bool(false)

*/

Expected result:
----------------
The expected result is to see real paths of the files under the /tmp directory. It works if the iterator is iterated directly, without being converted to an array first.

Actual result:
--------------
The actual result is all real paths are FALSE since after having been converted to an array, the directory iterator is in an invalid state.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-05-12 13:15 UTC] cmb@php.net
-Type: Bug +Type: Documentation Problem
 [2021-05-12 13:15 UTC] cmb@php.net
In my opinion, DirectoryIterator is badly designed; it should not
extend SplFileInfo, but rather yield SplFileInfo instances on
iteration.  However, this is not something that can fixed at this
point in time, or at the very least that would require careful
consideration and the RFC process[1].

The behavior should, however, be explicitly mentioned in the docs.

[1] <https://wiki.php.net/rfc/howto>
 [2021-05-12 15:09 UTC] phpbugs at notanemail dot org
> In my opinion, DirectoryIterator is badly designed; it should not
> extend SplFileInfo, but rather yield SplFileInfo instances on
> iteration. 

FilesystemIterator was introduced, in PHP 5.3.0, whose default behaviour is to use SplFileInfo instances as the "current" values.

DirectoryIterator should have been deprecated at that time. No-one should be using DirectoryIterator: rather FilesystemIterator (or RecursiveDirectoryIterator, which extends FilesystemIterator).
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Mon Jul 26 13:01:24 2021 UTC