PHP
Project: Quiz app
Overview of the 5-lesson quiz project: a Q&A app with OOP and arrays.
Project: Quiz app
In this 5-lesson project you'll build a quiz app. Each lesson adds one piece, and by the final lesson you'll complete a working mini application.
You'll use what you learned in previous groups: classes, constructors, methods and the foreach loop. Throughout the project you'll design a Question class that holds the question text, options and the correct answer index and checks answers. Then you'll add a Quiz class to walk all questions and compute the score.
Project roadmap
The project has five lessons. In the second lesson you'll write the question class and its constructor with properties for text, options and the correct answer index. In the third you'll add an isCorrect method that compares the user's chosen index with the correct answer using ===. In the fourth you'll use a Quiz class with a foreach loop to compute the score. In the final lesson you'll combine all parts and complete the working quiz app with a summary method.
Exercise Define the Question class
Write the first piece of this project. Define a class named Question. Add a public string $text = ""; property (empty string default). Then create an instance with $q = new Question();, set the text with $q->text = "What is PHP?"; and print it with echo $q->text;.
Show example solution
Declare the class with class Question { ... }, add public string $text = "";. Create an instance with $q = new Question();, set the text with $q->text = "What is PHP?"; and print with echo $q->text;.
Example solution:
<?php
// Define the Question class and create an instance
class Question {
public string $text = "";
}
$q = new Question();
$q->text = "What is PHP?";
echo $q->text;
Test yourself
-
Why write a quiz app with OOP?
- Question, options and answer stay in one unit; code is reusable.
- It can be written with loops only, OOP makes no difference.
- OOP does not work without a database.
- OOP is only for web pages.
Show answer
Question, options and answer stay in one unit; code is reusable. — Correct. A class bundles question data and answer checking in one unit, so you can reuse the code in other projects.
-
Complete the question class name
class ____ {
public string $text = "";
}
Show answer
class Question {
public string $text = "";
}
-
Match the quiz project concepts
- Question
- Text and options
- Option
- One of the choices
- Correct answer
- Expected option index
- Score
- Number correct
Next lesson: Designing a question class