Re: object references lose local variables
| From: | Joel Ricker | Date: | Sat, 29 Sep 2001 04:26:49 +0000 |
| Subject: | Re: object references lose local variables | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-69250@lists.php.net to get a copy of this message | ||
I tried to ask this person if anybody answered his question personally or
not but it appears the e-mail address isn't real (a@a.com). Understanable.
Does anyone know about this or did anyone send em an e-mail about this?
Just starting work on my first serious OOP project beyond a handful of basic
classes and am interested in any information or problems associated with it.
Joel
: I'd like to ask your help to figure out why PHP objects are stripped of
: their local variables when you add the objects to an array.
: Shouldn't these be references, not shallow copies?
:
: The code below is a simple org chart.
: I create three instances, each is added to a global array called orgs[].
:
: Each instance has a child, but when you add them to orgs[]
: they lose their children.
: I used & to create a reference, not a copy, but the problem remains.
:
: Please reply by email to steve@orangeimagineering-no-spam-please.com,
: but without the "-no-spam-please".
:
: When run in PHP Version 4.0.6, I get this output.
: Notice that $apple retains its local value of $children,
: but the same object, pushed onto $orgs[0], loses its local value.
:
: --- output web page----
:
: <Apple has 1 children >
: <Banana has 1 children >
: <Cherry has 1 children >
:
: <Apple has 0 children >
: <Banana has 0 children >
: <Cherry has 0 children >
:
:
: ----------- source code ------
: <?php
: // A simple (buggy) Org chart package
: global $orgs;
: $orgs = array();
:
: class Org {
: var $name;
: var $children;
:
: function Org ($iname) {
: global $orgs;
: $this->name = $iname;
: $this->children = array();
: $orgs[] = & $this; // Each Org is added to the array $orgs[]
: }
:
: function prettyprint() {
: return "<".$this->name." has
".count($this->children)."
: children >";
: }
: } // end class Org
:
: // Create three Orgs
: $apple = new Org("Apple");
: $banana = new Org("Banana");
: $cherry = new Org("Cherry");
:
: // Arrange them hierarchically
: $apple->children[] = $banana;
: $banana->children[] = $cherry;
: $cherry->children[] = "none";
: ?>
:
: <html>
: <body bgcolor=white>
: <?php
:
: echo($apple->prettyprint()."<br>");
: echo($banana->prettyprint()."<br>");
: echo($cherry->prettyprint()."<p>");
:
: echo($orgs[0]->prettyprint()."<br>");
: echo($orgs[1]->prettyprint()."<br>");
: echo($orgs[2]->prettyprint()."<br>");
: ?>
: </body>
: </html>
:
:
: --
: PHP General Mailing List (http://www.php.net/)
: To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net
: For additional commands, e-mail: php-general-help@lists.php.net
: To contact the list administrators, e-mail: php-list-admin@lists.php.net