Justtechjobs.com Find a programming school near you






Online Campus Both


php-general | 2001092

[PHP] object references lose local variables From: a (a <email protected>)
Date: 09/26/01

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 <email protected>,
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>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: php-general-unsubscribe <email protected>
For additional commands, e-mail: php-general-help <email protected>
To contact the list administrators, e-mail: php-list-admin <email protected>