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:

  1. Define a class `Fruit` with two properties: `$name` and `$color`.
  2. Add a `set_name($name)` method to set the name.
  3. Add a `get_name()` method to return the name.
  4. 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:

  1. Rewrite `Fruit` to use `__construct($name, $color)`.
  2. The constructor should assign the properties on object creation.
  3. Add a `get_color()` method.
  4. 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:

  1. Create a `Strawberry` class that extends `Fruit`.
  2. Add a new `message()` method that prints "Am I a fruit or a berry?"
  3. 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:

  1. In `Fruit`, make `$name` public.
  2. Make `$color` protected.
  3. Make `$weight` private.
  4. 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:

  1. Define a constant `LEAVING_MESSAGE` in a `Goodbye` class.
  2. Set it to "Thank you for visiting W3Schools.com!".
  3. 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:

  1. Define an abstract class `Car` with an abstract method `intro()`.
  2. Create `Audi` and `Volvo` classes that extend `Car`.
  3. 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:

  1. Define an interface `Animal` with a `makeSound()` method.
  2. Create a `Cat` class that implements it and prints "Meow".
  3. 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:

  1. Define a trait `message1` with a `msg1` method that prints "OOP is fun!"
  2. Use the trait inside a `Welcome` class.
  3. 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:

  1. Use `new mysqli` to connect to `localhost` with user `username` and password `password`.
  2. Check the connection and print the error (`connect_error`) if it fails.
  3. 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:

  1. Write an SQL query to select `id`, `firstname`, `lastname` from `MyGuests`.
  2. Execute the query and get the result.
  3. 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();
?>
Smart Editor

Write code and see the result instantly

Try it free