0

试图了解面向对象的 PHP。我有一个递归方法来返回评论及其回复并将它们编译成一个平面数组$comments_list

<?php

class RedditPosts
{
    public function get_post_ids($from, $limit)
    {
        // GET POSTS
        $list = json_decode(file_get_contents("http://www.reddit.com/$from.json?limit=$limit"));
        sleep(2); //after every page request

        $post_ids = array();
        foreach($list->data->children as $post) {
            $post_ids[] = $post->data->id;
        }
        return $post_ids;
    }
}

class RedditComments
{
    static $comments_list = array();

    public function get_comments($post_id)
    {
        $comments_object = json_decode(file_get_contents("http://www.reddit.com/comments/$post_id.json"));
        sleep(2);

        $top_comments = $comments_object[1]->data->children;
        //var_dump($top_comments);
        self::get_sub_comments($top_comments);
    }

    static function get_sub_comments($root_comments)
    {
        foreach($root_comments as $comment)
        {
            self::$comments_list[] = $comment;
            //echo $comment->data->body . "<br/>"

            if ($comment->data->replies != '')
            {
                self::get_sub_comments($comment->data->replies->data->children);
            }
        }
        var_dump(self::$comments_list);
        return self::$comments_list;

    }
}

/******************************MAIN************************************/

$ps = new RedditPosts();
$my_posts = $ps->get_post_ids("r/learnprogramming", 2);

$cm = new RedditComments();
$my_comments = $cm->get_comments($my_posts[0]);
var_dump($my_comments);

?>

我在返回它之前做了一个 var_dump 并且它被填充并且看起来正确但是当我在方法之外调用它时它是空的。可能是范围的问题,但我是新手,无法弄清楚我在哪里碰壁了。帮助表示赞赏!

4

1 回答 1

1

您不会从get_post_ids. self::get_sub_comments($top_comments);应该是self::get_sub_comments($top_comments);

于 2012-08-30T22:31:52.417 回答