I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is s
Disclaimer: none of this code was tested, but it definitely gets the point across.
Choose a name for the variable you want to be available in the global scope. Within the function, assign a value to the name index of the $GLOBALS array.
function my_function(){
//...
$GLOBALS['myGlobalVariable'] = 42; //globalize variable
//...
}
Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.
echo $myGlobalVariable; //outputs "42"
//
?>
To access your global variable from a non-global scope such as a function or an object, you have two options:
$GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.
//
function a(){
//...
global $myGlobalVariable;
echo $myGlobalVariable; // outputs "42"
//...
}
function b(){
//...
echo $GLOBALS['myGlobalVariable']; // outputs "42"
echo $myGlobalVariable; // outputs "" (nothing)
// ^also generates warning - variable not defined
//...
}
//
Please use global variables in any language with caution, especially in PHP.
See the following resources for discussion of global variables:
http://chateau-logic.com/content/dangers-global-variables-revisited-because-php
http://c2.com/cgi/wiki?GlobalVariablesAreBad