My question is why $instance
and $reference
become null?
PHP references operate in a funny way. I'm going to break out a real-life analogy.
Imagine you have a cup. The cup is full of water.
The cup is a variable. The water is the contents of the variable.
Any references you create point at the cup, not the water.
If you replace the water in the cup with coffee, then all of the references to that cup suddenly contain the same coffee.
And when you empty the cup out, all of the references to the cup are suddenly empty.
Now, objects are quite fun. You see, when you assign them to variables, it actually does so kind of by reference. But objects-by-ref aren't normal references. From the PHP interactive prompt:
php > class Foo { public $bar; }
php > $f = new Foo();
php > $f->bar = 1;
php > $f_copy = $f;
php > $f_copy->bar = 2;
php > echo $f->bar;
2
Not what you expected, right? It gets funnier.
php > $f_copy = $f;
php > $copy_ref = &$f_copy;
php > $copy_ref->bar = 3;
php > echo $f->bar;
3
That is a bit more expected. But is this?
php > $f_copy = null;
php > print_r($copy_ref);
php > var_export($copy_ref);
NULL
php > print_r($f);
Foo Object
(
[bar] => 3
)
As you can see, even though we completely emptied out the variable containing the reference to our object, the original object was untouched, even though that object was placed into the copy by reference!
Welcome to PHP, where things like this are normal. I suggest frequent checks of your own sanity.
Edit: Oh, one more thing. If you need to make a real copy of the object, you have to clone
it:
php > $not_f = clone $f;
php > $not_f->bar = 'I am not $f';
php > echo $f->bar;
3
php > echo $not_f->bar;
I am not $f
It also works on refs:
php > $not_f_copy = $not_f;
php > $not_copy_ref = &$not_f_copy;
php > $headsplode = clone $not_copy_ref;
php > $not_f->bar = 'No, I am Spartacus!';
php > echo $headsplode->bar;
I am not $f
Oh, and before someone asks: In some languages, references work at the value level, not the variable level. Perl is a good example here. If you create a reference to a variable, then reassign the original, the reference still contains the original value. I came to PHP through Perl, and this seemingly small difference drove me up the wall.