basic php help needed

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
iffo
Forum Commoner
Posts: 37
Joined: Thu Oct 05, 2006 11:56 am

basic php help needed

Post 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 )

)
nowaydown1
Forum Contributor
Posts: 169
Joined: Sun Apr 27, 2008 1:22 am

Re: basic php help needed

Post 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.
Post Reply