Image

Imagehipmaestro wrote in Imagephp

Recursion and OO PHP?

I started trying to do some object-oriented PHP stuff, but I'm stuck on a problem that seems to be caused by trying to invoke a method recursively, each time on a different object.




The code:



Class TreeNode {
  var $nodeTitle;
  var $childNodes;
  
  function TreeNode($nodeTitle) {
    $this->nodeTitle = $nodeTitle;
    $this->childNodes = array();
  }
  
  function addChild($child) {
    print "Adding $child->nodeTitle to $this->nodeTitle\n";
    $this->childNodes[] = $child;
  }
  
  function printTree($indent) {
    $kids = $this->childNodes;
    $count = count($kids);
    print $indent.$this->nodeTitle." ($kids contains $count children)\n";
    for ($i = 0; $i < $count; $i++)
    {
      $kids[$i]->printTree(" ".$indent);
    }
  }
}

$food = new TreeNode("food");

  $fruit = new TreeNode("fruit");
  $food->addChild($fruit);

    $apples = new TreeNode("apples");
    $fruit->addChild($apples);

    $oranges = new TreeNode("oranges");
    $fruit->addChild($oranges);

    $grapes = new TreeNode("grapes");
    $fruit->addChild($grapes);
    
      $whiteGrapes = new TreeNode("white grapes");
      $grapes->addChild($whiteGrapes);

      $redGrapes = new TreeNode("red grapes");
      $grapes->addChild($redGrapes);

  $grains = new TreeNode("grains");
  $food->addChild($grains);


print "\nfruit obviously has three children:\n";
$fruit->printTree("* ");

print "\ngrapes has two, though when examined from fruit (see above), it has 0:\n";
$grapes->printTree("* ");

print "\nThis should display the whole tree, but all its children show up as being empty:\n";
$food->printTree("* ");



The output:



Adding fruit to food
Adding apples to fruit
Adding oranges to fruit
Adding grapes to fruit
Adding white grapes to grapes
Adding red grapes to grapes
Adding grains to food

fruit obviously has three children:
* fruit (Array contains 3 children)
  * apples (Array contains 0 children)
  * oranges (Array contains 0 children)
  * grapes (Array contains 0 children)

grapes has two, though when examined from fruit (see above), it has 0:
* grapes (Array contains 2 children)
  * white grapes (Array contains 0 children)
  * red grapes (Array contains 0 children)

This should display the whole tree, but all its children show up as being empty:
* food (Array contains 2 children)
  * fruit (Array contains 0 children)
  * grains (Array contains 0 children)


For some reason, although $this->childNodes (aka $kids) is an Array each time, its elements don't show up after the first level of recursion.





Am I doing something wrong, or is this a limitation of PHP? Thanks.