PHP Exam 5: OOP and Databases (10 mixed exercises)
PHP Exam 5: Object-Oriented Programming (OOP)
Test your skills in building scalable software with OOP concepts and database access.
Exercise 1
Classes & Objects
Create a simple class:
- Define a class `Fruit` with two properties: `$name` and `$color`.
- Add a `set_name($name)` method to set the name.
- Add a `get_name()` method to return the name.
- Create an object, set its name to "Apple", and print it.
Solution
<?php
class Fruit {
public $name;
public $color;
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
echo $apple->get_name();
?>
Exercise 2
Constructor
Use a constructor:
- Rewrite `Fruit` to use `__construct($name, $color)`.
- The constructor should assign the properties on object creation.
- Add a `get_color()` method.
- Create an "Apple" object with color "Red" and print its name and color.
Solution
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "Red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
Exercise 3
Inheritance
Inherit properties in another class:
- Create a `Strawberry` class that extends `Fruit`.
- Add a new `message()` method that prints "Am I a fruit or a berry?"
- Create a `Strawberry` object and call parent/child methods.
Solution
<?php
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "Red");
$strawberry->message();
echo $strawberry->get_name();
?>
Exercise 4
Access Modifiers
Control property visibility:
- In `Fruit`, make `$name` public.
- Make `$color` protected.
- Make `$weight` private.
- Try to access each property outside the class and explain in a comment.
Solution
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
// $mango->color = 'Yellow'; // ERROR
// $mango->weight = '300'; // ERROR
?>
Exercise 5
Class Constants
Use constants inside a class:
- Define a constant `LEAVING_MESSAGE` in a `Goodbye` class.
- Set it to "Thank you for visiting W3Schools.com!".
- Print the constant using the class name and `::`.
Solution
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::LEAVING_MESSAGE;
?>
Exercise 6
Abstract Classes
Create a general structure:
- Define an abstract class `Car` with an abstract method `intro()`.
- Create `Audi` and `Volvo` classes that extend `Car`.
- Implement `intro()` in each subclass with a different message.
Solution
<?php
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}
$audi = new Audi("Audi");
echo $audi->intro();
?>
Exercise 7
Interfaces
Define a contract to implement:
- Define an interface `Animal` with a `makeSound()` method.
- Create a `Cat` class that implements it and prints "Meow".
- Create a `Dog` class that implements it and prints "Bark".
Solution
<?php
interface Animal {
public function makeSound();
}
class Cat implements Animal {
public function makeSound() {
echo "Meow";
}
}
class Dog implements Animal {
public function makeSound() {
echo "Bark";
}
}
$cat = new Cat();
$cat->makeSound();
?>
Exercise 8
Traits
Reuse code:
- Define a trait `message1` with a `msg1` method that prints "OOP is fun!"
- Use the trait inside a `Welcome` class.
- Create a `Welcome` object and call `msg1`.
Solution
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
Exercise 9
Database Connection (MySQLi Connect)
Connect to a MySQL database:
- Use `new mysqli` to connect to `localhost` with user `username` and password `password`.
- Check the connection and print the error (`connect_error`) if it fails.
- If it succeeds, print "Connected successfully".
Solution
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Exercise 10
Select Data
Fetch and display data:
- Write an SQL query to select `id`, `firstname`, `lastname` from `MyGuests`.
- Execute the query and get the result.
- Use a `while` loop to display each row.
Solution
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>