PHP读取目录树,文件名的一个类:Directory Reader Object



 function main(){
 //Set Variables
 $testDirName = "../php/";
 $fileListArray = array();
 $dirListArray = array();

$aDirectory = new DirReader($testDirName);

// Store File List in Array
$fileListArray = $aDirectory->getFileList();
$dirListArray = $aDirectory->getDirList();

echo "\n";
echo "</pre><pre>\n";

echo "Reading Directory: ".  $aDirectory->getDirPath() ."\n";
echo "Current Directory: ". getcwd() ."\n";

echo "-- Files in Directory --\n";
foreach ($fileListArray as $filename) {
    echo "File: $filename\n";

echo "\n-- Sub Directories --\n";
foreach ($dirListArray as $filename){
    echo "Sub dir: $filename\n";
echo "</pre>

class DirReader{
private $dh; # Directory Handle
private $basedir; # Base Directory passed to the object
private $fileNameArray=array();
private $dirNameArray=array();

function __construct($dirname){
$this->basedir = $dirname;
$this->dh = dir($dirname) or die($php_errormsg);

function parseDirectory(){
$filename = "";
while (false !== ($filename = $this->dh->read())){
$fullpath = $this->basedir . '/' . $filename;
if (is_file($fullpath)){
array_push($this->fileNameArray, $filename);
array_push($this->dirNameArray, $filename);

// Get all the files in the directory
function getFileList(){
return $this->fileNameArray;

// Get all the sub directories in the directory
function getDirList(){
return $this->dirNameArray;

function getDirPath(){
return $this->dh->path;

The class is defined on lines 35-57. Lines 36-39 define the object properties. The private keyword is new to PHP5. Lines 41-44 initialize variables get the directory passed to it when the object is created. The constructor then calls the parseDirectory function which reads the directory contents into separate file and directory arrays. The code that reads the info, line 49, comes almost directory out of the documentation. This example uses the object oriented approach to reading a directory handle. Line 51 checks if this is a file or directory. Then, the file name gets pushed into the appropriate place. The methods on lines 60 to 72 allow you to retrieve your desired information.

点此下载此文件: dirreader