Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- Objects being modified by reference?
- Mark Smith
January 6, 2010, 5:03 pm
rate this thread
I just spent the last few hours tracking down a bug, that was due to a
faulty assumption on my part.
I was under the impression that when references to a variable are
modified, a copy is created unless the & operator is used to explicity
modify the original too.
This does not seem to be the case, at least with objects:
In the above example 2 identical objects are dumped, even though only
the copy was modified...
What is the best way to avoid this behavior?
Re: Objects being modified by reference?
In PHP 5 all objects are internally addressed with a kind of reference
(not to confuse with PHP's &-references, which are a different thing),
so in fact $test and $test2 both refer to the same instance.
If you want to get a real copy, you have to clone the object:
$test2 = clone $test;