Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do objects automatically inherit values from another object initiated before or after?

Tags:

oop

php

Here Student's class method and variable get affected and present in other object too i.e. $obj1, why does this happen?

class Student {
    public $name;
    public $age;
    public function callme() {
        return 'called';
    }
}

$obj = new Student();
$obj1 = $obj;
$obj->name = 'David';
$obj->age = 12;
echo '<pre>';
print_r($obj);
print_r($obj1);
echo $obj1->callme();

ouput :

Student Object
(
    [name] => David
    [age] => 12
)
Student Object
(
    [name] => David
    [age] => 12
)
called
like image 320
AmmyTech Avatar asked Aug 30 '16 12:08

AmmyTech


2 Answers

This behaviour is explained here, when you do the following:

$obj = new Student();
$obj1 = $obj;

$obj1 is actually a reference to $obj so any modifications will be reflected on the original object. If you need a new object, then declare one using the new keyword again (as that's what it's for) as such:

$obj = new Student();
$obj1 = new Student();

(Also, I see @Wizard posted roughly the same thing half way through me writing this but I'll leave this here for sake of examples)

like image 97
Sworrub Wehttam Avatar answered Nov 15 '22 01:11

Sworrub Wehttam


As of PHP 5, $obj and $obj1 hold a copy of the object identifier, which points to the same object. Read http://php.net/manual/en/language.oop5.references.php

like image 28
Wizard Avatar answered Nov 14 '22 23:11

Wizard