为了好玩,我把它搅在一起:
class FileFinder
{
private $onFound;
private function __construct($path, $onFound, $maxDepth)
{
// onFound gets called at every file found
$this->onFound = $onFound;
// start iterating immediately
$this->iterate($path, $maxDepth);
}
private function iterate($path, $maxDepth)
{
$d = opendir($path);
while ($e = readdir($d)) {
// skip the special folders
if ($e == '.' || $e == '..') { continue; }
$absPath = "$path/$e";
if (is_dir($absPath)) {
// check $maxDepth first before entering next recursion
if ($maxDepth != 0) {
// reduce maximum depth for next iteration
$this->iterate($absPath, $maxDepth - 1);
}
} else {
// regular file found, call the found handler
call_user_func_array($this->onFound, array($absPath));
}
}
closedir($d);
}
// helper function to instantiate one finder object
// return value is not very important though, because all methods are private
public static function find($path, $onFound, $maxDepth = 0)
{
return new self($path, $onFound, $maxDepth);
}
}
// start finding files (maximum depth is one folder down)
$count = $bytes = 0;
FileFinder::find('.', function($file) use (&$count, &$bytes) {
// the closure updates count and bytes so far
++$count;
$bytes += filesize($file);
}, 1);
echo "Nr files: $count; bytes used: $bytes\n";
您传递基本路径、找到的处理程序和最大目录深度(-1 禁用)。找到的处理程序是您在外部定义的函数,它从函数中给定的路径中传递相对路径名find()
。
希望它有意义并帮助你:)