RecursiveIterator not working as expected

67 views Asked by At

Here is my function:

protected function getContents($absoluteDirectoryPath = false, $recursive = false, $filter = "/.$/") {
    if(!$absoluteDirectoryPath) return false;
    $iterator  = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($absoluteDirectoryPath));
    $files = new RegexIterator($iterator, $filter);
    return $iterator;
}

And i call it like this:

$pageFiles = $this->getContents($pagepath);

foreach($pageFiles as $file) {
    echobr("PageFile: " . $file->fileName);
}

This is the error I get:

Notice: Undefined property: SplFileInfo::$fileName

If I var_dump $pageFiles I get this:

object(DirectoryIterator)#5 (4) {
  ["pathName":"SplFileInfo":private]=>
  string(68) "/home/domain/example/public/home/home.php"
  ["fileName":"SplFileInfo":private]=>
  string(12) "home.php"
  ["glob":"DirectoryIterator":private]=>
  bool(false)
  ["subPathName":"RecursiveDirectoryIterator":private]=>
  string(0) ""
}

Whats going on? Why can't I loop through the results? There are 4 files in this directory and I should be able to output the filename.

1

There are 1 answers

0
Progman On

The SplFileInfo class does not have a (public) filename or fileName property. However, it has a getFilename() method. You can use it to get the filename:

foreach($pageFiles as $file) {
    echobr("PageFile: " . $file->getFilename());
}