Note that there are some explanatory texts on larger screens.

plurals
  1. POUnderstanding OOP Principles in passing around objects/values
    text
    copied!<p>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.</p> <p>So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers.</p> <pre><code>Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment </code></pre> <p>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:</p> <pre><code>$question = new Question; $question-&gt;load($this_question_id); // from the URL probably echo $question-&gt;getTitle(); </code></pre> <p>To load the answers, I imagine it's something like this ("A"):</p> <pre><code>$answers = new Answers; $answers-&gt;loadFromQuestion($question-&gt;getID()); // or $answers-&gt;loadFromQuestion($this_question_id); while($answer = $answers-&gt;getAnswer()) { echo $answer-&gt;showFormatted(); } </code></pre> <p>Or, would you do ("B"):</p> <pre><code>$answers-&gt;setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers-&gt;loadFromQuestion(); // the ID would be found via $this-&gt;question-&gt;getID() instead of from the argument passed in while($answer = $answers-&gt;getAnswer()) { echo $answer-&gt;showFormatted(); } </code></pre> <p>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.</p> <p>Thanks, Hans</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload