Jump to content


Photo

Globals


  • Please log in to reply
2 replies to this topic

#1 johnnyk

johnnyk
  • Members
  • PipPipPip
  • Advanced Member
  • 126 posts

Posted 28 July 2006 - 02:09 AM

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?
Rediscover the Web:
<a href="http://www.spreadfir...;t=219"></a><br />

#2 corbin

corbin
  • Staff Alumni
  • Advanced Member
  • 8,129 posts

Posted 28 July 2006 - 02:23 AM

<?
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...
Why doesn't anyone ever say hi, hey, or whad up world?

#3 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 28 July 2006 - 10:43 AM

You can either return it as corbin has shown above or make your var2 var global like so:
function whatever2()
{
    global $var2;

    $var2 = "hi";
}
// call our function, first
whatever2();

// now we will be able to use our variable from the function
echo $var2;

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:
<?php

function getVars()
{
    $var = 'hello';
    $var2 = 'hey';
    $var3 = 'bye';

    return array($var, $var2, $var3);
}

$vars = getVars();

echo '<pre>' . print_r($vars, true) . '</pre>';
?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users