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

Here the method and the variable of the Student class fall and are present in another object, i.e. $ obj1, why is this happening?

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(); 

output:

 Student Object ( [name] => David [age] => 12 ) Student Object ( [name] => David [age] => 12 ) called 
+6
source share
2 answers

This behavior is explained here when you do the following:

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

$obj1 is actually a reference to $obj , so any changes will be reflected in the original object. If you need a new object, then declare it with the new keyword again (as it is for it) as such:

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

(Also, I see that @Wizard sent about the same thing halfway through me by writing this, but I will leave it here for examples)

+3
source

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

+1
source

All Articles