Usage of setInfoClass() on DirectoryIterator vs on RecursiveDirectoryIterator

Posted by Gordon on Stack Overflow See other posts from Stack Overflow or by Gordon
Published on 2010-04-16T17:17:57Z Indexed on 2010/04/16 17:23 UTC
Read the original article Hit count: 179

Filed under:
|
|
|

I've ran into an inconsistent behavior when using setInfoClass to set a custom SplFileInfo class to a DirectoryIterator versus setting it to a RecursiveIterator. The method description states:

Use this method to set a custom class which will be used when getFileInfo and getPathInfo are called. The class name passed to this method must be derived from SplFileInfo.

Consider this custom SplFileInfo

class A extends SplFileInfo {
    public function test() {
        printf("I am of class %s\n", __CLASS__);
    }
}

and my iterators

$iterator = new DirectoryIterator('.');

and

$iterator = new RecursiveDirectoryIterator('.');

Now I'd expect those two to behave the same when I do

$iterator->setInfoClass('A');
foreach($iterator as $file) {
    $file->test();
}

and output 'I am of A' for each $file encountered and in fact, the RecursiveDirectoryIterator will do that. But the DirectoryIterator will raise

Fatal error:  Call to undefined method DirectoryIterator::test()

so apparently the InfoClass does not get applied when iterating over the files. At least not directly, because when I change the code in the foreach loop to

$file->getPathInfo()->test();

it will work for the DirectoryIterator. But then the RecursiveDirectoryIterator will raise

Fatal error:  Call to undefined method SplFileInfo::test()

Like I said, I'd expect those two to behave the same, but apparently getFileInfo and getPathInfo don't get called in the DirectoryIterator, which I consider a bug. So if there is any Iterator experts out there, please help me understand this.

Thanks.

© Stack Overflow or respective owner

Related posts about spl

Related posts about iterators