Can not access Global Vars inside a function?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pdescham49
Forum Newbie
Posts: 1
Joined: Sat May 10, 2003 8:01 pm
Location: Canada

Can not access Global Vars inside a function?

Post by pdescham49 »

Basically I am feeling out PHP for a couple projects. It's pretty simple. comming form ASP jscript to PHP. I kinda like some of the differences

However their is one thing that is annoying me and i hope this isn't the way it is. allow me to explain:

Why can I not use Global Var's inside a funtion?

<?
global $USState, $theString;
$USState = array();

$USState[name][0] ="AL(Alabama)";
$USState[name][1] ="AK(Alaska)";

$theString = "HIMOM";

// just a dummy function.

function dostuff()
{
$myCount = count($USState[name]);
printf('[global]$theString:'.$theString);
printf('[globalArray]$USState[name]'.$USState[name]);
}
dostuff();
?>

I hope I am doing something wrong. :)
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

This might help.
chris22
Forum Newbie
Posts: 11
Joined: Tue Apr 22, 2003 9:45 pm

Post by chris22 »

Code: Select all

<?
// don't need to global it here, its already global.
// don't need to "initialize" variables like in C, just set it.
$USState = array(); 

// always quote named indexes, otherwise it throws a low level error
$USState&#1111;'name']&#1111;0] ="AL(Alabama)"; 
$USState&#1111;'name']&#1111;1] ="AK(Alaska)"; 

$theString = "HIMOM"; 

// just a dummy function. 

function dostuff() &#123;
global $USState&#1111;'name'], $theString;
// or
$USState = $GLOBALS&#1111;'USState'];
$theString = $GLOBALS&#1111;'theString'];

$myCount = count($USState&#1111;name]);
// only use printf if you need to format it, like currency or hexidecimal...
// use just plain print to print an ordinary string.

// single quotes print *literally* what's inside the quotes.  doubles will parse variables within the quotes (but increase overhead).
print $theString . ': ' . $USState&#1111;name] . '<br>'; 
&#125; 
dostuff(); 
?>
Post Reply