0
0
PHPprogramming~20 mins

Interface declaration and implementation in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Interface declaration and implementation
📖 Scenario: You are building a simple system to manage different types of vehicles. Each vehicle must be able to start its engine. You will use an interface to ensure all vehicles have a startEngine method.
🎯 Goal: Create an interface called Vehicle with a method startEngine. Then create two classes, Car and Motorcycle, that implement this interface. Each class should have its own version of the startEngine method. Finally, create objects of these classes and call their startEngine methods to see the output.
📋 What You'll Learn
Create an interface named Vehicle with a method startEngine.
Create a class Car that implements the Vehicle interface.
Create a class Motorcycle that implements the Vehicle interface.
Each class must have its own startEngine method that prints a unique message.
Create objects of Car and Motorcycle and call their startEngine methods.
💡 Why This Matters
🌍 Real World
Interfaces are used in real-world software to define common behaviors that different types of objects must have, like vehicles all needing to start their engines.
💼 Career
Understanding interfaces is important for writing clean, maintainable code and is a common requirement in many programming jobs, especially in object-oriented programming.
Progress0 / 4 steps
1
Create the Vehicle interface
Create an interface called Vehicle with a method declaration public function startEngine();.
PHP
Need a hint?

Use the interface keyword followed by the interface name. Inside, declare the method startEngine without a body.

2
Create the Car class implementing Vehicle
Create a class called Car that implements the Vehicle interface. Define the method startEngine inside Car to print "Car engine started".
PHP
Need a hint?

Use class Car implements Vehicle. Inside, define startEngine method that uses echo to print the message.

3
Create the Motorcycle class implementing Vehicle
Create a class called Motorcycle that implements the Vehicle interface. Define the method startEngine inside Motorcycle to print "Motorcycle engine started".
PHP
Need a hint?

Similar to Car, create Motorcycle class implementing Vehicle and define startEngine method with the correct message.

4
Create objects and call startEngine methods
Create an object $car of class Car and an object $motorcycle of class Motorcycle. Call startEngine on both objects, printing each result on a new line.
PHP
Need a hint?

Create objects using new keyword. Call methods with ->. Use echo "\n"; to print a new line between outputs.