Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference

Tags:

oop

php

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?

like image 543
user699535 Avatar asked Dec 02 '25 04:12

user699535


1 Answers

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.

like image 85
KingCrunch Avatar answered Dec 03 '25 17:12

KingCrunch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!