PHP Tutorials Examples Introduction to SPL

<?php
    
/*** class definition to extend Directory Iterator class ***/
    
class DirectoryReader extends DirectoryIterator
    
{
        
// constructor.. duh!
        
function __construct($path)
        {
            
/*** pass the $path off to the parent class constructor ***/
            
parent::__construct($path
);
        }

        

/*** return the current filename ***/
        
function current()
        {
            return 
parent::getFileName
();
        }

        

/*** members are only valid if they are a directory ***/
        
function valid()
        {
            if(
parent::valid())
            {
                if (!
parent::isDir())
                {
                    
parent::next();
                    return 
$this->valid();
                }
            return 
TRUE;
            }
            return 
FALSE
;
        }

    } 

// end class

    

try
    {
        
/*** a new iterator object ***/
        
$it = new DirectoryReader('./');
        
/*** loop over the object if valid ***/
        
while($it->valid())
        {
            
/*** echo the current object member ***/
            
echo $it->current().'<br />';
            
/*** advance the internal pointer ***/
            
$it->next();
        }
    }
    catch(
Exception $e)
    {
        echo 
'No files Found!<br />'
;
    }

?>

Overload Standard PHP Library 的 Iterator