Rupert
Rupert

Reputation: 1639

Globals, objects and references in php - how do they work?

I understand that by using "=" objects are assigned by reference and for other variable and for datatypes like strings and integers you need to use "=&" to assign by reference. When you assign an object by reference explicitly using "=&", it seems to not affect assignment. However when you assign the object to a global it does.

Consider the following:

<?php

$global_obj = null;

class my_class {

    var $value;

    public function __construct() {
        global $global_obj;

        $global_obj =& $this;
        $GLOBALS['some_var'] = $this;
    }
}

$a = new my_class();
$a->my_value = 5;
$global_obj->my_value = 10;

echo 'A: ' . $a->my_value; //5
echo '<br />';
echo 'Global Object: ' . $global_obj->my_value; //10
echo '<br />';
echo 'Globals Array Value: ' . $some_var->my_value; //5

?>

If you remove the ampersand in the code above $this is assigned to $global_obj by reference. My question is why does having the ampersand in there seemingly stop this from happening?

Thanks

Upvotes: 0

Views: 93

Answers (1)

newacct
newacct

Reputation: 122439

What is happening here is that $global_obj is a reference to the variable $this. $this is a pseudo-variable that exists inside methods to be a reference to the current object. But who knows what happens to $this when it goes outside of the method scope. It is probably a bad idea to have a reference to $this.

In fact, if you investigate it a bit further, after your constructor returns, if you examine $global_obj, its value is null. The PHP engine probably sets $this to null after the method exits (but this is not documented anywhere), and your $global_obj, since it is a reference to the variable $this, follows it. When you set an attribute on null, it instantiates a new object of class stdClass automatically, so it seems to succeed. But of course this is a completely different object than the one in $a.

Upvotes: 2

Related Questions