Pezmc Posted March 30, 2007 Share Posted March 30, 2007 I am not a newbie I have just never figured out how to do this (taught my self php). I have a function say function socks(test,sock) { echo $test echo "I am a fary:" echo $sock $total = $test * $sock; } How can I get the total out of the function to use in other places as a variable, is there a returning function or something? Quote Link to comment https://forums.phpfreaks.com/topic/44928-getting-stuff-out-of-a-function/ Share on other sites More sharing options...
obsidian Posted March 30, 2007 Share Posted March 30, 2007 You need to have your function return the value. Then, you can assign that function call to a variable: <?php function socks($test, $sock) { $total = $test * $sock; return $total; } echo socks(5, 6); $val = socks(6, ; echo $val; ?> Quote Link to comment https://forums.phpfreaks.com/topic/44928-getting-stuff-out-of-a-function/#findComment-218157 Share on other sites More sharing options...
Daniel0 Posted March 30, 2007 Share Posted March 30, 2007 You could also make the variables global inside the function, then it would, well, do it globally instead of internally inside the function. Example: <?php $var = "hi"; function change_variable($new) { global $var; $var = $new; // or $_GLOBALS['var'] = $new } change_variable("hello"); // $var now holds the value "hello" ?> Quote Link to comment https://forums.phpfreaks.com/topic/44928-getting-stuff-out-of-a-function/#findComment-218164 Share on other sites More sharing options...
obsidian Posted March 30, 2007 Share Posted March 30, 2007 You could also make the variables global inside the function, then it would, well, do it globally instead of internally inside the function. Example: <?php $var = "hi"; function change_variable($new) { global $var; $var = $new; // or $_GLOBALS['var'] = $new } change_variable("hello"); // $var now holds the value "hello" ?> Global variables are very often bad news to use. They are definitely frowned upon more and more as PHP progresses. If you're wanting your function to act upon the variable or object directly, you'd be much better off to pass it in by reference: <?php $var = "hi"; function change_variable($new, &$old) { $old = $new; } change_variable('hello', $var); echo $var; // now holds the value 'hello' ?> Quote Link to comment https://forums.phpfreaks.com/topic/44928-getting-stuff-out-of-a-function/#findComment-218172 Share on other sites More sharing options...
Daniel0 Posted March 31, 2007 Share Posted March 31, 2007 Yeah, but if you have an object you use a lot (e.g. $db), then it might be annoying to pass $db to a lot of functions, in that case global might be better. Quote Link to comment https://forums.phpfreaks.com/topic/44928-getting-stuff-out-of-a-function/#findComment-218648 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.