ldlonline Posted August 17, 2009 Share Posted August 17, 2009 I just started PHP lessons and I have the following: <?php $a=5; $b=8; function add($a,$b) { $total=($a+$b); return $total; } echo "$a + $b = " . add($a,$b) . "<br />"; ?> What happens to the variable $total? If I say echo $total it doesn't print anything. Why can't I say: echo "$a + $b = $total"; ? Thanks in advance! Quote Link to comment https://forums.phpfreaks.com/topic/170595-php-return-function/ Share on other sites More sharing options...
oni-kun Posted August 17, 2009 Share Posted August 17, 2009 Everything in the function stays in the function's private scope. $total is something that the function returns, the total of $a and $b. Also, 'return $total' can be substituted for 'echo $total', they're just different structures. <?php $a=5; //Public variable, can be accessed here or in a function $b=8; function add($a,$b) { $total=($a+$b); //Private, not public scope return $total; } echo "$a + $b = " . add($a,$b) . "<br />"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/170595-php-return-function/#findComment-899811 Share on other sites More sharing options...
Psycho Posted August 17, 2009 Share Posted August 17, 2009 The issue you are having is with what is called variable scope (google for more info). A variable created in a function is not available outside the function, unless you specify it as such. Personally, I would write your code like this function add($a,$b) { return ($a+$b); } $a=5; $b=8; $total = add($a, $b); echo "$a + $b = $total<br />"; Quote Link to comment https://forums.phpfreaks.com/topic/170595-php-return-function/#findComment-899812 Share on other sites More sharing options...
ldlonline Posted August 17, 2009 Author Share Posted August 17, 2009 Gotcha! Thank you for the quick replies Quote Link to comment https://forums.phpfreaks.com/topic/170595-php-return-function/#findComment-899816 Share on other sites More sharing options...
oni-kun Posted August 17, 2009 Share Posted August 17, 2009 Gotcha! Thank you for the quick replies You're welcome! Remember to hit 'Topic Solved' in the bottom left corner if we answered your question. Quote Link to comment https://forums.phpfreaks.com/topic/170595-php-return-function/#findComment-899818 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.