2012-09-09 63 views
2

對不起,如果標題混亂,但我想獲得所有評論和他們的遞歸函數的答覆。問題是頂級註釋對象與註釋有不同的數據結構。頂級評論可從$comment_object->data->children訪問,而所有評論回覆均可從$comment->data->replies訪問。這是我到目前爲止有:參數數據結構變化時的遞歸函數?

public function get_top_comments() 
{ 
    $comments_object = json_decode(file_get_contents("http://www.reddit.com/comments/$this->id.json")); 
    sleep(2); // after every page request 

    $top_comments = array(); 
    foreach ($comments_object[1]->data->children as $comment) 
    { 
     $c = new Comment($comment->data); 
     $top_comments[] = $c; 
    } 
    return $top_comments; 
} 

public function get_comments($comments = $this->get_top_comments) //<-- doesn't work 
{ 
    //var_dump($comments); 

    foreach ($comments as $comment) 
    { 
     if ($comment->data->replies != '') 
     { 
      //Recursive call 
     } 
    } 
} 

我試圖分配$comments = $this->get_top_comments作爲遞歸函數的默認參數,但我想PHP不支持呢?我必須在函數中使用if-else塊來分隔不同的結構嗎?

回答

3

我只是將默認值get_comments()設爲NULL,然後檢查它是否爲空;如果是,請使用頂部評論。無論如何,你不想讓評論通過NULL

public function get_comments($comments = NULL) 
{ 
    //var_dump($comments); 

    if (is_null($comments)) 
     $comments = $this->get_top_comments; 

    foreach ($comments as $comment) 
    { 
     if ($comment->data->replies != '') 
     { 
      //Recursive call 
     } 
    } 
} 

這是the PHP docs一個例子是怎麼做的。請注意文檔中的註釋:

默認值必須是常量表達式,而不是(例如)變量,類成員或函數調用。

+0

感謝您澄清這一點,這解釋了我得到了'T變量預期'的錯誤。 – pdizz