In PHP, I have this simple class
<?php
class Person {
var $first_name = "factory method";
}
?>
The question I have is if I have:
$person1 = new Person();
$person2 = $person1;
$person1 = null;
var_dump($person1);
var_dump($person2);
what I get is: both $person1 = null and $person2 is not null at all, it seems $person1 and $person2 are not pointing to the same thing at all.
but when I do something like below:
$person1 = new Person();
$person2 = $person1;
$person2->first_name = "programming";
echo $person1->first_name;
echo $person2->first_name;
I got the same thing "programming", so I think the both $person1 and $person2 are pointing to the same thing.
Could someone explain to me why is it like that?
Dont mix pointers with references. After $person1 = null;
this variable refers to something different, because you assign something different to the variable. With
$person1 = $person2 = new Person;
Both refers the same single object instance. With $person2->first_name
you change this object, not the variable, that still refers to the object.
After you set $person1 to null in the first example it is no longer referring to the Person object that you created, but $person2 still is.
In the second example both $person and $person2 refer to the same object.
See the PHP manual on References.