参数的数据结构变化时的递归函数?

时间:2012-09-09 20:30:32

标签: php recursion overloading reddit

很抱歉,如果标题令人困惑,但我正在尝试使用递归功能获取所有评论及其回复。问题是顶级注释对象具有与注释不同的数据结构。从$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块来分隔不同的结构?

1 个答案:

答案 0 :(得分: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中的一个例子。请注意文档中的此评论:

  

默认值必须是常量表达式,而不是(例如)变量,类成员或函数调用。

相关问题