In my code:
<?php $var1 = 0; //I want `$var1` to retain its value in all functions `abc()` and `xyz()` abc(); function abc() { global $var1; $varDatabase = 10; //a value from database $var1 = &$varDatabase; //$var1 set as reference xyz(); //$var1 is changed in xyz() function echo $var1; //I expect value 110 here but it return last value 10 } function xyz() { global $var1; $var1 = $var1 + 100; } ?>
My variable $var1
is set as a pointer/reference to another variable $varDatabase
. $var1
is updated in a function xyz()
, and I expect its new updated value in calling function after xyz()
is executed. That is why I have set $var1
as global
, but still it does not give me updated value after xyz()
is executed.
All I want is$var1
to retain its value in all functions abc()
and xyz()
Advertisement
Answer
Global variables are implemented by making the variable a reference to the corresponding $GLOBALS
element, i.e.
global $var1;
is equivalent to
$var1 = &GLOBALS['var1'];
But if you then redefine it to be a reference to some other variable, it’s no longer a reference to the $GLOBALS
element, so it’s not a global variable any more.
See the documentation References with global and static variables
If you want $var1
to retain its value, make it a global variable, but don’t make it a reference to $varDatabase
. Just do
$var1 = $varDatabase;