简体   繁体   中英

RecursiveIterator not working as expected

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM