PHP / Programming · 2009-11-06

PHP- Globals

This one drove me nuts for a while so here is how to work with global scope in PHP classes.

From within one function, if you want a variable of any sort to be globally visible, then you must use the keyword global, like this:

function Test(){
global $var_name;
// now use it, if you'd like to
$var_name[] = "value1";
$var_name[] = "value2";
$var_name[] = "value3";
}

Now just because you’ve declared it as global, doesn’t yet mean that it’s totally global… until you declare it within the function that you need it, like this:

function Next(){
// load it
global $var_name;
// now you can loop through that array
foreach($var_name as $k=>$v){
echo $v;
}
}

So, all other facts learned in other programming languages do not apply here. PHP is really unique.