Jeg har lavet en quiz klasse til dig...:
quiz.class.php:
<?php
class Quiz
{
//MAX NUMBERS OF QUESTIONS
private $MaxQuestions;
//CONTAIN QUESTIONS
private $Questions;
//QUESTION NUMBER (STARTS AT 1)
private $QuestionNumber = 1;
//CONTAIN ERRORS
private $Error = 0;
//CONSTRUCTOR
public function __construct($MaxQuestions = 9)
{
$this->MaxQuestions = $MaxQuestions;
if(!isset($_SESSION['Question']))
{
$_SESSION['Question'] = 1;
}
}
public function CheckAnswer($Answer)
{
if($Answer == $this->Questions[$_SESSION['Question']]['Answer'])
{
return true;
}else{
return false;
}
}
//SET QUESTION
public function AddQuestion($Question, $Answer)
{
if($this->Error == 0)
{
//CHECK IF QUESTION IS A STRING
if(is_string($Question))
{
//CHECK MAXIMUM QUESTIONS
if($this->MaxQuestions >= $this->QuestionNumber)
{
//SET QUESTION
$this->Questions[$this->QuestionNumber]['Question'] = $Question;
//SET ANSWER
$this->Questions[$this->QuestionNumber]['Answer'] = $Answer;
$this->QuestionNumber++;
}else{
$this->Error(100);
}
}else{
$this->Error(101);
}
}else{
$this->Error(102);
}
}
public function ShowForm($Question)
{
//SHOW IF THE ERROR IS NOT SET
if($this->Error == 0 && count($this->Questions) != 0)
{
if(count($this->Questions) >= $_SESSION['Question'])
{
echo "<h1>".$Question." . ".$this->Questions[$Question]['Question']."</h1>\n";
echo "<form action='' method='POST'>\n";
echo "<input type='text' name='Answer' size='20'>\n";
echo "<input type='submit' value='Accepter?' name='Button'/>\n";
echo "</form>\n";
}else{
echo "<h1>No more questions..</h1>";
}
}else{
$this->Error(103);
}
}
public function Error($x)
{
$this->Error = 1;
switch ($x) {
case 100:
$ErrorText = "There must be maximum ".$this->MaxQuestions." questions";
break;
case 101:
$ErrorText = "The answer was not allowed, or in the class array...";
break;
case 102:
$ErrorText = "The question must be of the type string...";
break;
case 103:
$ErrorText = "The form failed to be created...";
break;
default:
$ErrorText = "Error found";
}
echo "<div id='Error'>".$ErrorText."</div>";
}
}
?>
example.php:
<?php
session_start();
include("quiz.class.php");
$Quiz = new Quiz();
$Quiz->AddQuestion("Spørgsmål1","1");
$Quiz->AddQuestion("Spørgsmål2","2");
$Quiz->AddQuestion("Spørgsmål3","3");
$Quiz->AddQuestion("Spørgsmål4","4");
$Quiz->AddQuestion("Spørgsmål5","5");
$Quiz->AddQuestion("Spørgsmål6","6");
$Quiz->AddQuestion("Spørgsmål7","7");
$Quiz->AddQuestion("Spørgsmål8","8");
$Quiz->AddQuestion("Spørgsmål9","9");
if(isset($_POST['Button']) && $Quiz->CheckAnswer($_POST['Answer']))
{
$_SESSION['Question']++;
}else{
echo "Wrong answer try again..";
}
$Quiz->ShowForm($_SESSION['Question']);
?>
Indlæg senest redigeret d. 11.03.2010 19:33 af Bruger #7728