Look at a simple recursive instance
Example 1
| The code is as follows: |
Copy code |
|
Function demo ($ ){
Static $ sum = 1;
If ($ a> 1 ){
$ Sum * = $;
Demo (-- $ );
} Else {
$ A = $ sum;
}
Return $ sum;
}
Echo demo (10 ); |
Example 2
Traverse directories
| The code is as follows: |
Copy code |
|
<? Php
Class listdir {
Var $ depth;
Var $ dirname;
Var $ list;
Var $ tostring;
Function listdir ($ dir ){
$ This-> dirname = $ dir;
$ This-> depth = 0;
$ This-> tostring = "";
}
// Save the result to a multi-dimensional array
Function getlist ($ dir = ""){
If ($ dir = "") $ dir = $ this-> dirname;
$ D = @ dir ($ dir );
While (false! ==( $ Item = $ d-> read ()))
{
If ($ item! = "." & $ Item! = "..")
{
$ Path = $ dir. "/". $ item;
If (is_dir ($ path )){
$ This-> depth + = 1;
$ This-> getlist ($ path );
} Else {
$ This-> list [$ this-> depth] [] = $ item;
}
}
}
$ This-> list [$ this-> depth] ['Directory'] = $ dir;
$ This-> depth-= 1;
$ D-> close ();
Return $ this-> list;
}
// Escape results
Function tostring ($ dir = ""){
If ($ dir = "") $ dir = $ this-> dirname;
$ D = @ dir ($ dir );
$ This-> tostring. = "<UL> n ";
$ This-> tostring. = "Directory:". $ dir. "n ";
While (false! ==( $ Item = $ d-> read ()))
{
If ($ item! = "." & $ Item! = "..")
{
$ Path = $ dir. "/". $ item;
If (is_dir ($ path )){
$ This-> depth + = 1;
$ This-> tostring ($ path );
} Else {
$ This-> tostring. = "<LI>". $ item. "</LI> n ";
}
}
}
$ This-> depth-= 1;
$ D-> close ();
$ This-> tostring. = "</UL> n ";
Return $ this-> tostring;
}
}
$ Wapdir = "jquery ";
$ D = new listdir ($ wapdir );
Echo $ d-> tostring ();
?>
Output result:
<UL>
Directory: jquery
<LI> jquery-1.3.2.js </LI>
<LI> jquery-1.3.2.min.js </LI>
<LI> jquery-1.3.2-vsdoc2.js </LI>
<LI> test.html </LI>
<LI> common. js </LI>
<UL>
Directory: jquery/d
<LI> common. js </LI>
<LI> jquery-1.3.2.js </LI>
</UL>
</UL> |