Re: Function returning a reference - how ?!?
| From: | Tim Molendijk | Date: | Sun, 22 Dec 2002 03:43:27 +0000 |
| Subject: | Re: Function returning a reference - how ?!? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-129094@lists.php.net to get a copy of this message | ||
Wow!! You're my king! Thanks, that syntax is completely new to me!
Great, another thing learned today! :)
Cheers mate!
<reynardmh@netscape.net> wrote in message
news:4054F4E7.3CEF3A45.03432DC2@netscape.net...
>
> change your createParent function to return by reference:
>
> function &createParent()
> {
> return new Parent;
> }
>
> it returns 'two' and 'two' for me
>
> Regards,
> - reynard
>
> >Hi all,
> >
> >I came across the following weird situation. I don't get it, I hope some
of
> >you can explain the logic of it all.
> >
> >[begin code]-------------------------------
> ><?php
> >
> >/* Define class Parent. Its constructor sets an instance of Child in
> >property $child and passes itself to Child's constructor. */
> >class Parent
> >{
> > var $child;
> > var $property = 'one';
> >
> > function Parent()
> > {
> > $this->child = &new Child($this);
> > }
> >}
> >
> >/* Define class Child. Its constructor assigns a reference of the Parent
> >object that contains this Child object to property $parent. */
> >class Child
> >{
> > var $parent;
> >
> > function Child(&$p)
> > {
> > $this->parent = &$p;
> > }
> >}
> >
> >/* This function instantiates and returns a new Parent class. */
> >function createParent()
> >{
> > return new Parent;
> >}
> >
> >/* $p is a reference of the Parent object created by createParent(). */
> >$p = &createParent();
> >
> >/* The $property property of the Parent object is changed. */
> >$p->property = 'two';
> >
> >/* Since $p should be the same object as $p->child->parent, the following
> >should print twice the same. */
> >print $p->property . '<BR>';
> >print $p->child->parent->property . '<BR>';
> >
> >?>
> >[end code]-----------------------------------
> >
> >Now the problem is: IT DOES NOT PRINT TWICE THE SAME!!!
> >Instead it prints 'two' and then 'one', which indicates that
> >$p->child->parent is another object than $p. The problem is that the
object
> >*returned* by createParent() is not the same object as the object that is
> >*created* by createParent(). Just replace the line $p = &createParent();
by
> >$p = &new Parent(); -- this works perfectly fine! Conclusion:
createParent()
> >does not return the object it creates!
> >
> >Someone knows why this ain't working and how to solve it?!? Hope so,
can't
> >wait to hear from you guys.
> >
> >Thanks in advance,
> >
> >Tim Molendijk
>
>
> __________________________________________________________________
> The NEW Netscape 7.0 browser is now available. Upgrade now!
http://channels.netscape.com/ns/browsers/download.jsp
>
> Get your own FREE, personal Netscape Mail account today at
http://webmail.netscape.com/