RE: [PHP] Function returning a reference - how ?!?
| From: | reynardmh at netscape dot net | Date: | Sun, 22 Dec 2002 03:37:30 +0000 |
| Subject: | RE: [PHP] Function returning a reference - how ?!? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-129093@lists.php.net to get a copy of this message | ||
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/