ayaya Posted January 1, 2013 Share Posted January 1, 2013 <? function f($a) { if($a<2) { echo "before:".$a."</br>"; f($a+1); echo "after:".$a."</br>"; } } f(0); ?> Why the result is: before:0 before:1 after:1 after:0 Can anyone help? Quote Link to comment Share on other sites More sharing options...
trq Posted January 1, 2013 Share Posted January 1, 2013 Makes perfect sense to me. What exactly were you expecting? Quote Link to comment Share on other sites More sharing options...
Jessica Posted January 1, 2013 Share Posted January 1, 2013 Your code basically does this: call f(0); echo before: 0 call f(1); echo before: 1; call f(2); exit f(2) echo after: 1; exit f(1); echo after: 0; Quote Link to comment Share on other sites More sharing options...
ayaya Posted January 1, 2013 Author Share Posted January 1, 2013 (edited) exit f(2) echo after: 1; exit f(1); echo after: 0; Thank you for your help. But if exit f(2) and f(1), How comes the result after "afer"? I still don't understand it. Sorry I'm very stupid... Edited January 1, 2013 by ayaya Quote Link to comment Share on other sites More sharing options...
DavidAM Posted January 1, 2013 Share Posted January 1, 2013 Each invocation of the function is a separate occurance and gets its own local variables. The recursive call is NOT modifying $a. For that matter, you are not modifying it locally. If you want the recursive call to affect the local variable, you would have to pass by reference or return it: function f($a) { if($a<2) { echo "before:".$a."</br>"; $a = f($a+1); echo "after:".$a."</br>"; } return $a; } f(0); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.