johnnyk Posted July 28, 2006 Share Posted July 28, 2006 So you can call a global variable from a function:$var = 'hey';function whatever(){ echo $GLOBALS['hey'];}BUT, how would you do the reverse, something like:function whatever(){ $var2 = 'hey';}Now say after that I want to echo $var2, is that possible? Quote Link to comment https://forums.phpfreaks.com/topic/15847-globals/ Share on other sites More sharing options...
corbin Posted July 28, 2006 Share Posted July 28, 2006 <?function whatever() {$var2 = "hi";return $var2;}echo whatever();?>is the only way i know of to do what youre asking... i dont mess with functions very often though so theres prolly a better way... Quote Link to comment https://forums.phpfreaks.com/topic/15847-globals/#findComment-64943 Share on other sites More sharing options...
wildteen88 Posted July 28, 2006 Share Posted July 28, 2006 You can either return it as corbin has shown above or make your var2 var global like so:[code]function whatever2(){ global $var2; $var2 = "hi";}// call our function, firstwhatever2();// now we will be able to use our variable from the functionecho $var2;[/code]By I'd recommend you to use return rather than making your variables global. If you are going to be returning 2 or more variables. I'd return it as an array, and store the array in a variable, like so:[code]<?phpfunction getVars(){ $var = 'hello'; $var2 = 'hey'; $var3 = 'bye'; return array($var, $var2, $var3);}$vars = getVars();echo '<pre>' . print_r($vars, true) . '</pre>';?>[/code] Quote Link to comment https://forums.phpfreaks.com/topic/15847-globals/#findComment-65088 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.