0

Trying to grok object-oriented PHP. I have a recursive method to return comments and their replies and compile them to a flat array $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);

?>

I do a var_dump right before returning it and it is filled and looks correct but when I call it outside the method it is null. Probably an issue with scope but I'm new at this and cant figure out where and I've hit a wall. Help appreciated!

1
  • When you use static methods, it is not really OOP. Just you old procedural code written with syntax, that at first glance mimics object oriented code. Commented Aug 31, 2012 at 1:47

1 Answer 1

1

You don't return anything from get_post_ids. self::get_sub_comments($top_comments); should be self::get_sub_comments($top_comments);?

Sign up to request clarification or add additional context in comments.

1 Comment

AHH, I tried to return from get_sub_comments instead of get_comments. It works now, and I feel like an idiot. I need a break. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.