The programming technique in which a program calls itself is called recursion. Recursion as an algorithm is widely used in programming languages. A process or function has a method of directly or indirectly calling itself in its definition or description. It usually transforms a large and complex problem into a smaller problem similar to the original problem to solve. The recursive strategy only A small number of programs are needed to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of program code. The power of recursion lies in defining an infinite collection of objects with a finite number of statements. Generally speaking, recursion requires boundary conditions, a recursive forward segment, and a recursive return segment. When the boundary conditions are not met, the recursion advances; when the boundary conditions are met, the recursion returns.
This article mainly introduces how PHP uses recursion to calculate the folder size. The code is very simple to use and is recommended to everyone here. Send the code directly:
The code is as follows:
protected function dir_size($dir){ $dh = opendir($dir); //打开目录,返回一个目录流 $size = 0; //初始大小为0 while(false !== ($file = @readdir($dh))){ //循环读取目录下的文件 if($file!='.' and $file!='..'){ $path = $dir.'/'.$file; //设置目录,用于含有子目录的情况 if(is_dir($path)){ $size += $this->dir_size($path); //递归调用,计算目录大小 }elseif(is_file($path)){ $size += filesize($path); //计算文件大小 } } } closedir($dh); //关闭目录流 return $size; //返回大小 }
The above is the detailed content of PHP uses recursion to calculate folder size sample code. For more information, please follow other related articles on the PHP Chinese website!