Re: Assign by reference...
| From: | Benjamin Berman | Date: | Tue, 13 Jun 2000 22:15:27 +0000 |
| Subject: | Re: Assign by reference... | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-1770@lists.php.net to get a copy of this message | ||
Jason,
There was a reason that I put the "$obj->a = 1" line -after- the "$arr[]
= $obj" line. This is what assign by reference is all about: when you
change something in the original object, the change is reflected in all
references to the object. You switched around the two lines. Your code
puts a -copy- of the $obj into the array, and then the two copies could
diverge which is not good for OO programming.
ben.
venaas@nvg.ntnu.no wrote:
>
> On Tue, Jun 13, 2000 at 02:38:15PM -0700, Benjamin Berman wrote:
> > Both of these output "1,2". The same program could be written in java.
> > It is very natural in all three languages. My question is, can you do
> > it in PHP4?
>
> Yes, how about:
>
> class Obj {
> var $a;
> }
>
> $obj = new Obj();
> $obj->a = 1;
> $arr[] = $obj;
> $obj = new Obj();
> $obj->a = 2;
> $arr[] = $obj;
>
> while ($el = array_shift($arr))
> echo $el->a;