2013-05-07 52 views
0

我有一個類項目,用MYSQL和PHP創建一個OODB。PHP - 在一個對象中調用對象

目前我有填充對象框的表。我還有一個盒子類,它在構造時將從表中獲取數據,然後以相似的方式遞歸構造其子元素。這似乎運作良好。但我無法從子框中調用函數。

這裏是類:

class Box1 { 
    var $id; 
    var $pid; 
    var $children; 
    var $type; 
    var $content; 
    var $siblingorder; 

    function Box1($bId){ 

     $q ="SELECT * FROM `box` WHERE id =". $bId; 
     $r = mysql_query($q); 
     if ($r){ 
       $row = mysql_fetch_array($r); 
       $this->id=$bId; 
       $this->pid=$row[1]; 
       $this->children=$row[2]; 
       $this->type=$row[3]; 
       $this->siblingorder=$row[5]; 
       $this->content=$row[6]; 
       //echo $this->id."<br />"; 
       if(isset($this->children)){ 
       //echo $this->children."<br />"; 
       $kids = explode(',', $this->children); 
       foreach ($kids as $key => $value) { 
        $varname = "box".$value; 
        //global $$varname; 
        //echo $varname."<br>"; 
        $$varname = new Box1($value); 
       } 
      } 
     } 
    }//constructor 

    function display(){ 
     echo "<div style='border: solid 2px;'>"; 
     echo $this->id; 
     echo "<br />"; 
     if(isset($this->children)){ 
      $kids = explode(',', $this->children); 
     foreach ($kids as $key => $value) { 
       $varname = "box".$value; 
       //echo $varname."<br />"; 
       $$varname->display(); 
     } 
     } 
     echo "</div>"; 
    }//End DISPLAY 

    function update(){ 

    }//End UPDATE 

} 

這裏是調用構造函數和這反過來應該叫孩子框顯示功能顯示功能的代碼:

$box1 = new Box1(1); 
    $box1->display(); 

任何幫助或洞察力會非常感謝。

+0

這是一個變量範圍的問題。 'display()'不能訪問'$ box1',因爲它不在該函數的範圍內。我可能會創建一個兒童對象數組作爲對象的一個​​屬性。 – andrewsi 2013-05-07 17:21:24

回答

0

正如第一條評論所述,問題在於$$ varname是在構造函數中創建和分配的。但它在功能顯示中不存在。一旦調用構造函數 ,這些變量就不再存在。找一些代碼下面將告訴您如何讓孩子BOX1類型的對象的數組

class Box1 { 

    var $id; 
    var $pid; 
    var $children; 
    var $type; 
    var $content; 
    var $siblingorder; 

    function Box1($bId){ 

     $q ="SELECT * FROM `box` WHERE id =". $bId; 
     $r = mysql_query($q); 
     if ($r){ 
       $row = mysql_fetch_array($r); 
       $this->id=$bId; 
       $this->pid=$row[1]; 
       $this->children = array();//[*] 
       $this->type=$row[3]; 
       $this->siblingorder=$row[5]; 
       $this->content=$row[6]; 

       //now we fill this->children with objects of type Box1 
       if ($row[2] != '') { 
        $kids = explode(',', $row[2]); 
        foreach ($kids as $value) { 
         $this->children[] = new Box1($value); 
        } 
       } 
     } 
    }//constructor 

    function display(){ 
     echo "<div style='border: solid 2px;'>"; 
     echo $this->id; 
     echo "<br />"; 
     foreach ($this->chidren as $kid) { 
       $kid->display(); 
     } 
     echo "</div>"; 
    }//End DISPLAY 

    function update(){ 

    }//End UPDATE 

} 

[*]:在這裏我們決定孩子總是BOX1的數組。當然,如果沒有孩子,這個數組可以是空的。這是一個品味問題,有些人寧願讓孩子沒有孩子。但是在這種情況下,在遍歷display()中的$ this-> children之前,您必須檢查空值。

+0

經過一些非常小的調整,如添加l到 - > chidren,它就起作用了。非常感謝你。 – user2359107 2013-05-08 01:31:33