Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 454
  • Last Modified:

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
0
Xavior2K3
Asked:
Xavior2K3
  • 2
1 Solution
 
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
 
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

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now