Understanding OOP Principles in passing around objects/values

Posted by Hans on Stack Overflow See other posts from Stack Overflow or by Hans
Published on 2010-12-23T20:10:52Z Indexed on 2010/12/23 20:54 UTC
Read the original article Hit count: 380

Filed under:
|

I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand.

So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers.

Question
 - comment
 - comment
 - comment

 Answer
  -comment

 Answer
  -comment
  -comment
  -comment

 Answer
  -comment
  -comment

So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like:

$question = new Question;
$question->load($this_question_id); // from the URL probably
echo $question->getTitle();

To load the answers, I imagine it's something like this ("A"):

$answers = new Answers;
$answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id);
while($answer = $answers->getAnswer())
{
    echo $answer->showFormatted();
}

Or, would you do ("B"):

$answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question
$answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in
while($answer = $answers->getAnswer())
{
    echo $answer->showFormatted();
}

I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here.

Thanks, Hans

© Stack Overflow or respective owner

Related posts about php

Related posts about oop