Object Copied by Reference in PHP V5

Object Copied by Reference in PHP V5

di Mike Churchward -
Numero di risposte: 5
Immagine Core developers Immagine Plugin developers Immagine 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
Media dei voti: -
In riposta a Mike Churchward

Re: Object Copied by Reference in PHP V5

di 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 riposta a Mike Churchward

Re: Object Copied by Reference in PHP V5

di Eloy Lafuente (stronk7) -
Immagine Core developers Immagine Documentation writers Immagine Moodle HQ Immagine Peer reviewers Immagine Plugin developers Immagine 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. ammiccante

Ciao sorridente
In riposta a Eloy Lafuente (stronk7)

Re: Object Copied by Reference in PHP V5

di Tim Hunt -
Immagine Core developers Immagine Documentation writers Immagine Particularly helpful Moodlers Immagine Peer reviewers Immagine 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 riposta a Tim Hunt

Re: Object Copied by Reference in PHP V5

di Mike Churchward -
Immagine Core developers Immagine Plugin developers Immagine 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 riposta a Mike Churchward

Re: Object Copied by Reference in PHP V5

di 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