Variable Scope

  • Thread starter Thread starter GilesGuthrie
  • 8 comments
  • 685 views

GilesGuthrie

Staff Emeritus
Messages
11,038
United Kingdom
Edinburgh, UK
Messages
CMDRTheDarkLord
Does anyone here code using global variables? I'm having real difficulty with them. Like they're not working!

If I do the following:
PHP:
global $year;
$year = 2003;

function printyear()
{
   echo "From inside the function: ".$year;
}

echo "From outside the function: ".$year;

I get:
From inside the function: 0
From outside the function: 2003

Which isn't good. It's not life threatening, because it just means I have to pass the variable all the time, which is a pain. Am I being dense here?
 
Oh, right. Thanks for that Cory. I never would have thought to do it that way. Guess my grounding in C is a bit more pervasive than first thought!

Am now retreating back into Programmerville, as am coding PHP that writes Javascript. It's something of a head****!
 
Back