Page 1 of 1

basic php help needed

Posted: Mon Jun 09, 2008 10:24 pm
by iffo
Hi,

I am trying to create an array of objects of class 'My' and then print that array. What am I doing wrong here, i did not get any thing in
var $name when I print array. Or do you see anthing else wrong here?

Code: Select all

 
<?php
 
class My 
{ 
        var $name = ""; 
        var $children = array(); 
        
 
        function My($name) 
        { 
                $this->$name = $name; 
               
    } 
 
        function addChild($mynode) 
        { 
                $this->children[] = $mynode; 
                
        } 
} 
 
 
 
        $a = new My("John"); 
        $b = new My("Bob"); 
        $c = new My("Cat"); 
        $x = new My("Xon"); 
 
        $a->addChild($b); 
        $a->addChild($c); 
        $a->addChild($x); 
 
       print_r($a->children);
     
?> 
 

output

Array
(
[0] => node Object ( [name] => [children] => Array ( ) => B )
[1] => node Object ( [name] => [children] => Array ( ) [C] => C )
[2] => node Object ( [name] => [children] => Array ( ) [X] => X )

)

Re: basic php help needed

Posted: Wed Jun 11, 2008 9:33 pm
by nowaydown1
Check your constructor:

Code: Select all

 
$this->$name = $name; 
 
Your using $this->$name = $name. So instead you're winding up with what you posted in your print_r, an extra element on your array with the same key and value. I believe you want:

Code: Select all

 
$this->name = $name;
 
That will assign your value to the name member instead.