In PHP can someone explain cloning vs pointer reference?

Viewed 4153

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

$b = 1;
$a =& $b;
$a = 3;
echo $b;

will output 3 because changes made to $a are the same as changes made to $b. Conversely:

$b = 1;
$a = $b;
$a = 3;
echo $b;

should output 1.

If this is the case, why is the clone keyword necessary? It seems to me that if I set

$obj_a = $obj_b 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 ($obj_a = $obj_b). This caused a frustrating problem for me today while working with DateTime objects that I eventually fixed by doing basically:

$obj_a = clone $obj_b

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??

3 Answers
Related