0
0
PHPprogramming~20 mins

Why interfaces are needed in PHP - See It in Action

Choose your learning style9 modes available
Why interfaces are needed
📖 Scenario: Imagine you are building a system where different types of devices can connect and perform actions. Each device has its own way of working, but they all must follow some common rules to work well together.
🎯 Goal: You will create an interface to define common actions for devices, then create classes that follow this interface. This shows why interfaces are needed to ensure different classes share the same methods.
📋 What You'll Learn
Create an interface called DeviceInterface with a method connect()
Create two classes Printer and Scanner that implement DeviceInterface
Each class must have its own connect() method with a simple message
Create a variable $device to hold an instance of Printer
Call the connect() method on $device and print the result
💡 Why This Matters
🌍 Real World
Interfaces are used in software to ensure different parts follow the same rules, like devices connecting to a computer or apps using common features.
💼 Career
Understanding interfaces is important for writing clean, maintainable code and working with large projects where many developers create different parts that must work together.
Progress0 / 4 steps
1
Create the interface
Create an interface called DeviceInterface with a method connect() that has no body.
PHP
Need a hint?

An interface defines method names without code. Use interface keyword and declare connect() without body.

2
Create classes implementing the interface
Create two classes called Printer and Scanner that implement DeviceInterface. Each class must have a connect() method that returns a string: "Printer connected" for Printer and "Scanner connected" for Scanner.
PHP
Need a hint?

Use implements DeviceInterface after class name. Define connect() method with return statements.

3
Create a device variable
Create a variable called $device and assign it a new instance of the Printer class.
PHP
Need a hint?

Use $device = new Printer(); to create the object.

4
Call the connect method and print
Call the connect() method on the $device variable and print the returned string using echo.
PHP
Need a hint?

Use echo $device->connect(); to print the message.