Just read the online php recursion, and asked the big God, told me that recursion is to call itself. Didn't understand. Also on Baidu saw the Hanoi tower problem. I know what happened to Hanoi, but I still don't understand recursion. Look at the cows to give a simple and understandable example ...
Reply to discussion (solution)
function f ($n) { $out =-1; if ($n <0) echo "Input cannot be negative"; else if ($n ==0| | $n ==1) $out =1; else $out =f ($n-1) * $n; return $out;} Echo f (3);
The most classic example of factorial
function f ($n) { $out =-1; if ($n <0) echo "Input cannot be negative"; else if ($n ==0| | $n ==1) $out =1; else $out =f ($n-1) * $n; return $out;} Echo f (3);
The most classic example factorial of this good ... Well, it looks like the IQ's not enough.
F (3) The parameter of the first pass to the F function is 3 run to $out=f ($n-1) * $n; It's changed. $OUT=F (3) = f (2) *3;f (2) The result has not yet been made, so the F function is called again, this time the F (2) parameter is 2 run again to $out=f ($n-1) * $n; when it becomes $out=f (2) = f (1) * *; F (1) When you run this function, you run the else if ($n ==0| | $n ==1) This code so f (1) = 1; When you know the result of f (1), we return the previous $out=f (2) = f (1) * = 1*1 =1; $out =f (2) = f (1) * = 1*2; $out =f (3) = f (2) * = 2*3; result is 6