PHP Changing values in one Object changes values in another object

Viewed 23

When running the below code, the first var_dump returns 20 whereas the second var_dump returns 4 although I'm dumping the same variable without changing it?

I'm just giving a new object the value of the original object.

I'm not sure what I am missing, is there relationships between one object if it received a value from another object

What I'm actually trying to do is make a copy of the original object and bring changes to the second object while keeping the original object as is

$varObj = (object) ['id'=>'20','title'=>'Test ID 20','product'=>'4'];

var_dump($varObj -> id);
$varObjCopy = $varObj;
$varObjCopy -> id = $varObj -> product;
var_dump($varObj -> id);
1 Answers

As per Markus Zeller in the comment you have to clone the object

$varObjCopy = clone $varObj
Related