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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With