View Full Version : global variable

12-09-2010, 05:00 AM
function statistics_exit() {
global $user, $recent_activity;

i am a newbie of php, expect someone can explain it for me. why put the global keyword before the variable $user, $recent_activity. could i remove it? what's the difference between have the global or haven't the global

12-09-2010, 06:56 AM
In contrast to local variables, a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example:

$somevar = 15;
function addit() {
GLOBAL $somevar;
print "Somevar is $somevar";
This will produce following result.

Somevar is 16

12-09-2010, 07:51 AM
but if i want to not change the original $somevar's value, how should i do. thank you.

12-09-2010, 12:54 PM
many people will tell you that global variables are evil ... that's not entirely true but anyway, often a global is used when perhaps passing the value by reference would do the same trick...

$somevar = 15;
function addit($var) {
echo $somevar; //echos 15

/////////////pass by reference

function additbyreference(&$var){
echo $somevar; //echos 16

why $user can not be passed as an argument in your example I do not know, one might expect to see instead..

function statistics_exit( $user, $recent_activity) {
//or &$user, &$recent_activity