Correct way of setting a custom FileInfo class to an Iterator
Posted
by Gordon
on Stack Overflow
See other posts from Stack Overflow
or by Gordon
Published on 2010-04-03T21:16:18Z
Indexed on
2010/04/03
21:23 UTC
Read the original article
Hit count: 328
I am trying to set a custom class to an Iterator through the setInfoClass
method:
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.
My class is like this (simplified example):
class MyFileInfo extends SplFileInfo
{
public $props = array(
'foo' => '1',
'bar' => '2'
);
}
The iterator code is this:
$rit = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/file/path/'),
RecursiveIteratorIterator::SELF_FIRST);
Since RecursiveDirectoryIterator
is by inheritance through DirectoryIterator
also an SplFileInfo
object, it provides the setInfoClass
method (it's not listed in the manual, but reflection shows it's there). Thus I can do:
$rit->getInnerIterator()->setInfoClass('MyFileInfo');
All good up to here, but when iterating over the directory with
foreach($rit as $file) {
var_dump( $file );
}
I get the following weird result
object(MyFileInfo)#4 (3) {
["props"]=>UNKNOWN:0
["pathName":"SplFileInfo":private]=>string(49) "/some/file/path/someFile.txt"
["fileName":"SplFileInfo":private]=>string(25) "someFile.txt"
}
So while MyFileInfo
is picked up, I cannot access it's properties. If I add custom methods, I can invoke them fine, but any properties are UNKNOWN.
If I don't set the info class to the iterator, but to the SplFileInfo object (like shown in the example in the manual), it will give the same UNKNOWN result:
foreach($rit as $file) {
// $file is a SplFileInfo instance
$file->setInfoClass('MyFileInfo');
var_dump( $file->getFileInfo() );
}
However, it will work when I do
foreach($rit as $file) {
$file = new MyFileInfo($file);
var_dump( $file );
}
Unfortunately, the code I a want to use this in is somewhat more complicated and stacks some more iterators. Creating the MyFileInfo class like this is not an option.
So, does anyone know how to get this working or why PHP behaves this weird?
Thanks.
© Stack Overflow or respective owner