Page 1 of 1

Can not access Global Vars inside a function?

Posted: Sat May 10, 2003 8:01 pm
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. :)

Posted: Sat May 10, 2003 9:37 pm
by m3mn0n
This might help.

Posted: Sat May 10, 2003 9:42 pm
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(); 
?>