Correct way of setting a custom FileInfo class to an Iterator
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:
shell$ php --rc RecursiveDirectoryIterator
// ...
Method [ <internal:SPL, inherits SplFileInfo> public method setInfoClass ] {
- Parameters [1] {
Parameter #0 [ <optional> $class_name ]
}
}
All good up to here, but when iterating over the directory with
$rit->getInnerIterator()->setInfoClass('MyFileInfo');
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 $fil开发者_运维问答e) {
$file = new MyFileInfo($file);
var_dump( $file );
}
Unfortunately, the code I 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.
Can't tell you exactly why but it works with
class MyFileInfo extends SplFileInfo
{
public $props;
public function __construct($filename) {
$this->props = array(
'foo' => '1',
'bar' => '2'
);
parent::__construct($filename);
}
}
精彩评论