DirectoryIterator クラス

(PHP 5, PHP 7, PHP 8)

はじめに

DirectoryIterator クラスは、 ファイルシステムのディレクトリを閲覧するためのシンプルなインターフェイスです。

クラス概要

class DirectoryIterator extends SplFileInfo implements SeekableIterator {
/* メソッド */
public function __construct(string $directory)
public function current(): mixed
public function getBasename(string $suffix = ""): string
public function getExtension(): string
public function getFilename(): string
public function isDot(): bool
public function key(): mixed
public function next(): void
public function rewind(): void
public function seek(int $offset): void
public function __toString(): string
public function valid(): bool
/* 継承したメソッド */
public function SplFileInfo::getATime(): int|false
public function SplFileInfo::getBasename(string $suffix = ""): string
public function SplFileInfo::getCTime(): int|false
public function SplFileInfo::getFilename(): string
public function SplFileInfo::getGroup(): int|false
public function SplFileInfo::getInode(): int|false
public function SplFileInfo::getMTime(): int|false
public function SplFileInfo::getOwner(): int|false
public function SplFileInfo::getPath(): string
public function SplFileInfo::getPathname(): string
public function SplFileInfo::getPerms(): int|false
public function SplFileInfo::getSize(): int|false
public function SplFileInfo::getType(): string|false
public function SplFileInfo::isDir(): bool
public function SplFileInfo::isExecutable(): bool
public function SplFileInfo::isFile(): bool
public function SplFileInfo::isLink(): bool
public function SplFileInfo::isReadable(): bool
public function SplFileInfo::isWritable(): bool
public function SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public function SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public function SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public function SplFileInfo::__toString(): string
}

目次

add a note

User Contributed Notes 4 notes

up
58
krystianmularczyk at gmail dot com
17 years ago
Shows us all files and catalogues in directory except "." and "..".

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

?>
up
3
alvaro at demogracia dot com
8 years ago
DirectoryIterator is just an lightweight SplFileInfo iterator and its methods operate on whatever item the internal cursor points to. In other words:

<?php
$iterator = new DirectoryIterator('C:\\');
echo $iterator->getPathname();
?>

... will NOT print "C:\" but the path of the first file or subdirectory retrieved, e.g. "C:\$Recycle.Bin".
up
5
David Lanstein
17 years ago
DirectoryIterator::getBasename() has been also been available since 5.2.2, according to the changelog (not documented yet).  It takes a parameter $suffix, and is useful if, for instance, you use a naming convention for your files (e.g. ClassName.php).  

The following code uses this to add recursively All*Tests.php in any subdirectory off of tests/, basically, suites of suites.

<?php
// PHPUnit boilerplate code goes here

class AllTests {
    public static function main() {
        $parameters = array('verbose' => true);
        PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);
    }

    public static function suite() {
        $suite = new PHPUnit_Framework_TestSuite('AllMyTests'); // this must be something different than the class name, per PHPUnit
        $it = new AllTestsFilterIterator(
                  new RecursiveIteratorIterator(
                      new RecursiveDirectoryIterator(dirname(__FILE__) . '/tests')));

        for ($it->rewind(); $it->valid(); $it->next()) {
            require_once($it->current());
            $className = $it->current()->getBasename('.php');
            $suite->addTest($className::suite());
        }

        return $suite;
    }
}
?>

Also, the AllTestsFilterIterator above extends FilterIterator, and contains one method, accept():

<?php
class AllTestsFilterIterator extends FilterIterator {
    public function accept() {
        if (preg_match('/All.*Tests\.php/', $this->current())) {
            return true;
        } else {
            return false;
        }
    }
}
?>
up
8
rogier at dsone dot nl
13 years ago
Beware of the behavior when using FilesystemIterator::UNIX_PATHS, it's not applied as you might expect.

I guess this flag is added especially for use on windows.
However, the path you construct the RecursiveDirectoryIterator or FilesystemIterator with will not be available as a unix path.
I can't say this is a bug, since most methods are just purely inherited from DirectoryIterator.

In my test, I'd expected a complete unix path. Unfortunately... not quite as expected:

<?php
         // say $folder = C:\projects\lang

        $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
        $d_iterator = new RecursiveDirectoryIterator($folder, $flags);

        echo $d_iterator->getPath();

?>

expected result: /projects/lang (or C:/projects/lang)
actual result: C:\projects\lang
To Top