找到之前的一篇笔记,关于PHP遍历目录类。发布出来,加深印象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * Open Read Write Close Dir and File 
 * 
 * @author		Yaron [xyaron@gmail.com,http://yaron.org.cn]
 * @version		0.1
 * @package		
 */
 
class fileDirOpt {
	var $dirPath;
	function openDir($dirPath){
		$this->dirPath	= $dirPath;
		if (is_dir($dirPath)){
			$dir	= opendir($dirPath);
			return $dir;
		}else{
			die("$dirPath is Not a Directory");
		}
	}
	function closeDir($dir) {
		closedir($dir);
	}
	function listDir($dir){
		echo '<ol>';
		while($file = readdir($dir)){
			if($file!='.' && $file!='..'){	// filter . and ..
				$dd		= $this->dirPath;		// 
				$dd		= $dd.'/'.$file;
				echo "<li>$file</li>";
			}
			if(is_dir($dd) && $file!='.' && $file!='..') {	// is_dir 参数需要完整的路径
				$subDir	= $this->openDir($dd);
				$this->listDir($subDir);
				$this->closeDir($subDir);
			}
		}
		echo '</ol>';
		return true;
	}
}
 
$dirOpt	= new fileDirOpt();
$dirOpt->dirPath	= 'd:/xampp';
$dir	= $dirOpt->openDir($dirOpt->dirPath);
$dirOpt->listDir($dir);
$dirOpt->closeDir($dir);

一位牛人说,优秀的代码不需要注释!言外之意是说不用注释,阅读者就能很好的理解!笔者没有达到这个水平,还是稍稍注释,其实用到的都是最基本的目录函数。