cloudll Posted January 15, 2012 Share Posted January 15, 2012 I have just started using functions, and have been following a few tutorials. I think im misunderstanding returns. lets say i have the variables called $math1 an $math2 and i want to make $total = $math1 + $math2; i then use return $total; I then thought i could echo $total and it would work outside of the function but its giving me an error of an underfines variable. Could anyone explain what im doing wrong please? thanks Quote Link to comment Share on other sites More sharing options...
AyKay47 Posted January 15, 2012 Share Posted January 15, 2012 Okay, let's say you are returning $total from your function. Set the function itself to a variable, this will hold your $total value. Quote Link to comment Share on other sites More sharing options...
ManiacDan Posted January 15, 2012 Share Posted January 15, 2012 You're not quite understanding how it works. Functions are completely self-contained. Nothing outside the function knows anything about the contents of the function. The variables and methods used inside the function do not exist outside the function. Imagine that all your functions happen on another computer entirely. So when you assign something to $total inside your function, it doesn't do anything outside your function. Returning a value means that your function can be used in an assignment: function doAdd($a, $b) { $total = $a + $b; return $total; } //won't work: echo $total; //won't work: doAdd(1, 2); echo $total; //will work: $total = doAdd(2, 3); echo $total; -Dan Quote Link to comment Share on other sites More sharing options...
cloudll Posted January 15, 2012 Author Share Posted January 15, 2012 ah ok, i get that, thanks 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.