First, sorry for the stupid question, but I was reading an article in php.net and I couldn’t understand what exactly it says.
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
<?php
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null
var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
And this outputs this:
NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
}
$instance and $reference point to same place, I get this and I understand why we get NULL and NULL for them.
But what about $assigned? It’s it also pointing the place where $instance is stored? Why when we use $instance->var it affects $assigned, but when we set $instance to be null, there is no change for $assigned?
I thought that the all three variables point to one place in the memory, but obviously I’m wrong. Could you please explain me what exactly happens and what is $assigned? Thank you very much!
$referencepoints to the value of$instance, which is itself a reference to an object. So when you change the value contained by$instance,$referencereflects this change.$assigned, on the other hand, is a copy of the value of$instance, and independently points to the object itself to which$instancerefers. So when the value$instanceis updated to point to nothing (i.e.null),$assignedis not affected, since it still points to the object, and doesn’t care about the contents of$instance.