object references lose local variables

From: Date: Wed, 26 Sep 2001 21:39:02 +0000
Subject: object references lose local variables
Groups: php.general 
Request: Send a blank email to php-general+get-68926@lists.php.net to get a copy of this message
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 "&lt;".$this->name." has ".count($this->children)." children &gt;"; } } // 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>

« previous php.general (#68926) next »