Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 11 ■ SPL FILE AND DIRECTORY HANDLING^167

Listing 11-4. Using SplFileInfo and DirectoryIterator

$pathName = '/path/to/iterate/';

foreach(new DirectoryIterator($pathName) as $fileInfo) {
echo $fileInfo. "\n";
}

.

..

folder
file.ext

In addition to the typical SplFileInfo methods and the methods required by the Iterator
interface, DirectoryIterator implements one other method: isDot(), which is used to determine
if the current entry in the iterator is either the current (.) or parent (..) folders. This can be
useful to ensure that you do not try to open these special entries.

RecursiveDirectoryIterator
It is often desirable to operate on a path hierarchy, rather than just a single directory at a time.
For this purpose, you can use the RecursiveDirectoryIterator, which provides recursive iter-
ation, as well as methods to determine if a path has child directories. Its definition is shown in
Listing 11-5.

Listing 11-5. RecursiveDirectoryIterator Definition

class RecursiveDirectoryIterator
extends DirectoryIterator implements RecursiveIterator
{

const CURRENT_AS_FILEINFO 0x00000010;
const KEY_AS_FILENAME 0x00000020;
const NEW_CURRENT_AND_KEY 0x00000030;

function __construct($path, $flags = 0) {}
function key() {}
function current() {}
function hasChildren() {}
function getChildren() {}
function getSubPath() {}
function getSubPathname() {}

}

McArthur_819-9C11.fm Page 167 Thursday, February 28, 2008 7:49 AM

Free download pdf