Object Copied by Reference in PHP V5

Object Copied by Reference in PHP V5

by Mike Churchward -
Number of replies: 5
Picture of Core developers Picture of Plugin developers Picture of Testers
I just had a "holy crap" moment, and just in case others weren't aware of this, thought I'd publish it here.

In PHP V4.x, the statements:
$myobject = new Myclass();
$myobject2 = $myobject;
created two completely separate objects; one a copy of the other.

In PHP V5.x, $myobject2 is a reference to $myobject. That is, they point to exactly the same object. Changing one, changes the other.

Man, did that mess me up. I'm going to have to check all of my code now....

mike
Average of ratings: -
In reply to Mike Churchward

Re: Object Copied by Reference in PHP V5

by Richard Crawford -
This has come to bite me in the rear a couple of times for a Moodle installation I maintain for one of our clients.  It took me forever to track down the issue and resolve it.
In reply to Mike Churchward

Re: Object Copied by Reference in PHP V5

by Eloy Lafuente (stronk7) -
Picture of Core developers Picture of Documentation writers Picture of Moodle HQ Picture of Peer reviewers Picture of Plugin developers Picture of Testers
Yep,

and that's one of the reason about the clone() function that was introduced some time ago, so your code should be:

$myobject = new Myclass();
$myobject2 = clone($myobject );

and then you'll have 2 different objects, both under PHP 4 and PHP 5. wink

Ciao smile
In reply to Eloy Lafuente (stronk7)

Re: Object Copied by Reference in PHP V5

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
On the other hand, most of the time you don't really need a copy. You are just passing around one object to pass information.

So most of the time you don't want a copy, since making the copy wastes time and information. So generally this is a positive change (IMHO), but yes, you have to check your code.
In reply to Tim Hunt

Re: Object Copied by Reference in PHP V5

by Mike Churchward -
Picture of Core developers Picture of Plugin developers Picture of Testers
Typically, if I've made a copy, its because I want to preserve the original and make changes to a new one. Imagine my surprise when the original changed to!

mike
In reply to Mike Churchward

Re: Object Copied by Reference in PHP V5

by John Papaioannou -
Bit me as well; see the comments in class block_base, method _load_instance(). wink

After debugging that I don't think I 'll ever forget how to handle objects in the future. tongueout