Understanding how to inject object dependencies
- by Hans
I have an object that loads an instance of another object in a method.
$survey = new survey;
$question = new question($survey);
$question-load($question_id);
class question {
public function __construct(&$survey)
{
$this-survey = $survey;
}
public function load ($id)
{
// now a question is loaded
// want to load the survey that this question is in
$this->survey->load($this->get('survey_id')); // ** survey_id is a field in the questions table
// now $this->survey object has all the info about the survey this question is in
}
private function get($name)
{
// returns $name, if isset() from array that load() sets
} }
This is frying my brain, though, because it seems like $survey should come into $response already being a complete object. But, how do I do that, if I don't know what survey_id to load until I'm in the object? I am revamping a site and the most complex part is littered with this issue. TIA - Hans.