SPL Problem, DirctoryIterator returns a SplFileInfo by default

$it = new DirectoryIterator(…);

$it->current() will return an instance “SplFileInfo”,

could it be any other class like “MyFileInfo”? so I could add some member function to that class.

class MyFileInfo extends SplFileInfo {
...
}

See SplFileInfo::setInfoClass(). The DirectoryIterator is a weird little beast though; don’t be surprised if this doesn’t work with it. If you’re using PHP 5.3.0 or above, use the FilesystemIterator. :slight_smile:

You are indeed correct, give me a few minutes to have a play with it. :slight_smile:

Hi, Thank you for your reply.
the API says the SplFileInfo::setFileClass is used when user open the file with $file-> openFile(). But I don’t need to open the file, I just want to add some method to the default SplFileInfo, like:

class MyFileInfo extends SplFileInfo { 
    public function myMethod() {
        .....
    }
}

if the DirectoryIterator::current() could get a MyFileInfo, then I could use it like this:

foreach(new DirectoryIterator(..)  as $it) {
    $it->myMethod();
}

Take a peek at SplFileInfo::setFileClass, as DirectoryIterator extends this, it will be available to you. :slight_smile:

Hi Salathe, thanks for the information, our system is still PHP5.2, but I’ll keep this in mind.:slight_smile:

Hmmmm.


<?php
class ExtendedSplFileInfo extends SplFileInfo
{
  public function getFilename(){
    return strtoupper(parent::getFilename());
  }
}

$it = new DirectoryIterator('.');
$it->setInfoClass('ExtendedSplFileInfo');

foreach($it as $file){
  echo $file->getFileInfo()->getFilename(), "\
" ;
}
?>

This works, but it isn’t the desired interface. Gonna grab a coffee and come back to this.

I think you’re going to need a custom iterator to replace DirectoryIterator.

Off Topic:

Argh, beaten to the punch by Salathe. At least I’m on the right track though…

Thank you AnthonySterling, this is exactly what I need.
it’s not necessary to call getFileInfo() again ?

foreach($it as $file){
  echo $file->getFilename(), "\
" ;
}