Lahiru Liyanapathirana
Lahiru Liyanapathirana

Reputation: 393

array of objects in an object in php

I am fairly new to php. I have classes called quiz and question. And the class quiz can have one or many questions. I have done a java representation

class Question () {
 private int id;
 private String question;
 private String answer;
}

and the quiz class should be as follows,

class Quiz() {
 private int id;
 private List<Question> questionList;
}

my question is regarding how to represent the above java representation in php. please be kind enough to point me in the right direction.

Upvotes: 2

Views: 86

Answers (2)

miglio
miglio

Reputation: 2058

getter and setter:

class Question {
    private $id ;
    private $question;
    private $answer;
    public function __construct(){
    }
    public function setId($value){
        $this->id = $value;
    }
    public function setQuestion($value){
        $this->question = $value;
    }
    public function setAnswer($value){
        $this->answer = $value;
    }
    public function getId(){
        return $this->id;
    }
    public function getQuestion(){
        return $this->question;
    }
    public function getAnswer(){
        return $this->answer;
    }
}
class Quiz{
    private $id;
    private $questionList = array();
    public function __construct(){
    }
    public function setQuestionList($value){
        $this->questionList[] = $value;
    }
    public function getQuestionList(){
        return $this->questionList;
    }
}
//
$quiz = new Quiz();
//
$question = new Question();
$question->setId(1);
$question->setQuestion('question?');
$question->setAnswer('answer');
//
$quiz->setQuestionList($question);
//
$question = new Question();
$question->setId(2);
$question->setQuestion('question2?');
$question->setAnswer('answer2');
//
$quiz->setQuestionList($question);
//

//Getting questions
foreach($quiz->getQuestionList() as $object){
    echo $object->getId().' - '.$object->getQuestion().' - '.$object->getAnswer().'<br />';
}

Upvotes: 1

FlorianLB
FlorianLB

Reputation: 1

Generics type don't exist in standard PHP.

One way to represent such structure in PHP is :

class Question 
{
    private $id;
    private $question;
    private $answer;
}

class Quiz 
{
    private $id;

    /**
     * @var array<Question>
     */
    private $questionList = array();
} 

The docblock (@var ...) is just here to help others (and IDEs) to understand the structure of $questionList.

To add some check on $questionList content, you can use typed setter/adder :

public function addQuestion(Question $question)
{
    $this->questionList[] = $question;
}

Upvotes: 0

Related Questions