In PHP can someone explain cloning vs pointer reference?

JagDaniAddisa

New Member
To begin with, I understand programming and objects, but the following doesn't make much sense to me in PHP.In PHP we use the & operator to retrieve a reference to a variable. I understand a reference as being a way to refer to the same 'thing' with a different variable. If I say for example\[code\]$b = 1;$a =& $b;$a = 3;echo $b;\[/code\]will output 3 because changes made to $a are the same as changes made to $b. Conversely:\[code\]$b = 1;$a = $b;$a = 3;echo $b;\[/code\]should output 1.If this is the case, why is the clone keyword necessary? It seems to me that if I set\[code\]$obj_a = $obj_b\[/code\] then changes made to $obj_a should not affect $obj_b,conversely $obj_a =& $obj_b should be pointing to the same object so changes made to $obj_a affect $obj_b.However it seems in PHP that certain operations on $obj_a DO affect $obj_b even if assigned without the reference operator \[code\]($obj_a = $obj_b)\[/code\]. This caused a frustrating problem for me today while working with DateTime objects that I eventually fixed by doing basically:\[code\]$obj_a = clone $obj_b\[/code\]But most of the php code I write doesn't seem to require explicit cloning like in this case and works just fine without it. What's going on here? And why does PHP have to be so clunky??
 
Back
Top