PHP Objects & References

Hi,

I have 2 quick questions about references in PHP, firstly, if i did the following:

     $this->object = new Object();
     $var1 = $this->object;

Would $var1 contain a copy of $this->object, and hence clone it?

Secondly, If I did the following:

     $ref =& $this->object;
     $secondref = $ref;

Does that mean $secondref is a reference to $this->object ($secondref is set to the same memory location as $ref is set to)? Or does PHP treat $ref as the same as $this->object and hence would not contain a reference to it and possibly duplicate it?

Thanks for your help,

Mike
LVL 1
Xavior2K3Asked:
Who is Participating?
 
hernst42Commented:
For your case yes, but the references work a little bit different e.g.
$var1 =& $this->object;
$this->object = new Object();
$var1 == $this->object

in this case $ref and $this->object contain the same object, but
$var1 = $this->object;
$this->object = new Object();
$var1 != $this->object

So working with objects in php5 there is no need to use the &. It causes you more trouble than you can imagine. See http://www.php.net/manual/en/language.references.php#language.references.whatare
0
 
hernst42Commented:
1) depends on you php version in 4 you get a copy in 5 it's the same object

2) $ref is becoming an "alias" for $this->object, but again in php 4 you get a copy, in php5 it's the same object.

See http://www.php.net/manual/en/migration5.oop.php for difference between 4 and 5 in the object model.
0
 
Xavior2K3Author Commented:
Sorry, I forgot to mention I'm using PHP 5.

So does this mean these are equivalent?:

     $var1 = $this->object;
     $var1 =& $this->object;

And that after these statements:

     $ref =& $this->object;
     $secondref = $ref;

$this->object, $ref and $secondref all point the the same object?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.