The code
$global_obj = null;
class my_class
{
var $value;
function my_class()
{
global $global_obj;
$global_obj = &$this;
}
}
$a = new my_class;
$a->my_value = 5;
$global_obj->my_value = 10;
echo $a->my_value;
echoes 5, not 10.
“Upon first examination, it would seem that the constructor of my_class stores a reference to itself inside the $global_obj variable. Therefore, one would expect that, when we later change the value of $global_obj->my_value to 10, the corresponding value in $a would change as well. Unfortunately, the new operator does not return a reference, but a copy of the newly created object.”
I still don’t understand it, so can anyone please explain it differently, and help me understand?
Not sure why this is the way it works, but, if you remove the
&in front of$thiswhile assigning it to your global variable, it will work.To illustrate that, the following portion of code :
Gives the following output :
Here are the differences with your code :
&before$this: with PHP 5, there is no need for that, when working with objects__constructfor the constructorpublic/protected/private, and notvarfor propertiesAs a sidenote, the code you posted should have given you the following warning :
Notes :
E_ALLdoesn’t includeE_STRICT(source)EDIT after some more searching :
Going through the References Explained section of the PHP manual, and, more specifically the What References Do page, there is a warning given that says (quoting) :
And there is an example going with it.
Trying to use
$GLOBALSin your code, I have this portion of code :And I get the following output :
Which seems to work 😉
If I replace the
__constructmethod by this :It doesn’t work…
So it seems you should not use
global, here, but$GLOBALS.The explanation given in the manual is :
And, just so it’s said : using global variables is generally not quite a good idea — and, in this specific situation, it feels like a very bad idea…
(Now, if this question what just to understand why… Well, I can understand your curiosity 😉 )