recursivity with objects

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I am trying to do a script that is must print a tree of object (my
objects are some comments).

For more details, a "comment" is an object which can be at the top of
the tree (father), or which can be an answer to another comment
(children). There is no limit in father-children relation (a father can
have children, which can have children, which ...).

I have made 2 object, the comment and a comment contener (just an
array). Un comment is simply composed with a texte and an id.

Here is the code and my test failure.

I want to display the tree (commen id):

Explain : commen 1 has 3 answers (4-5-6), 2 & 3 have not answer. Comment
5 has one answer (7) which has one answer(8) ...

classe comments

     //comments array
     var $tab_comments;

     function comments()

     function addcomment($comment)
     {//add a comment into the array
}//end comments

class comment
{//the comment
     var $id;
     var $contenu;

     //children array
     var $tab_comments;

     function comment($num, $texte)

     function outprint()
         echo "I am comment number <br>";

     function printFils()
     {    //print all children
          foreach ($this->tab_comments as $comment)

     function addcomment($comment)
     {//add a children
}//fin classe comment

//Here is the test
$commentaires=new comments();

$commentaire1=new comment('1','commentaire 1');
$commentaire2=new comment('2','commentaire 2');
$commentaire3=new comment('3','commentaire 3');
$commentaire4=new comment('4','commentaire 4');
$commentaire5=new comment('5','commentaire 5');
$commentaire6=new comment('6','commentaire 6');
$commentaire7=new comment('7','commentaire 7');
$commentaire8=new comment('8','commentaire 8');
$commentaire9=new comment('9','commentaire 9');

//add fathers to contener

//children-father relationship


//Display $commentaire1

/* end test */

The result is :
I am comment number 1
I am comment number 4
I am comment number 5
I am comment number 6

This mean that the tree is not completly read and that I need help !!

Best regards


Re: recursivity with objects

pepete wrote:


Quoted text here. Click to load it

If you are using PHP4, this is because PHP4 passes values, not references by
default. You can fix this by modifying the the addcomment method definition
with a reference argument.

So, the way you have it now, when you add $commentaire5 to $commentaire1, a
copy of $commentaire5 is made. Any further changes to $commentaire5 are
made to the original variable, and not to the copy held by $commentaire1.

Your updated function definition should look like:

function addcomment(&$comment)

Read info about references on PHP website:

Site Timeline