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 [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 ------
// 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";

<body bgcolor=white>



PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to