我对php很新。我有一些叫做测验和问题的课程。课堂测验可以有一个或多个问题。我做了一个java表示
class Question () {
private int id;
private String question;
private String answer;
}
并且测验类应该如下,
class Quiz() {
private int id;
private List<Question> questionList;
}
我的问题是关于如何在php中表示上面的java表示。请善意指出我正确的方向。
答案 0 :(得分:1)
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 />';
}
答案 1 :(得分:0)
标准PHP中不存在泛型类型。
在PHP中表示此类结构的一种方法是:
class Question
{
private $id;
private $question;
private $answer;
}
class Quiz
{
private $id;
/**
* @var array<Question>
*/
private $questionList = array();
}
docblock(@var
...)就是为了帮助其他人(和IDE)理解$questionList
的结构。
要对$questionList
内容添加一些检查,您可以使用输入的setter / adder:
public function addQuestion(Question $question)
{
$this->questionList[] = $question;
}