Introduction
Abstract classes and interfaces help organize PHP applications by defining rules that other classes must follow. An abstract class can contain both normal and abstract methods, while an interface defines methods that implementing classes must provide. In this chapter, you will practise both concepts through beginner-friendly PHP examples. Abstract Classes and Interfaces in PHP practice questions with solutions to help you to understand the concepts.
Question 1: Create a Simple Abstract Class
Problem Statement
Create an abstract class named Animal with an abstract method makeSound(). Create a child class named Dog that implements the method and displays a barking message.
PHP Solution
<?php
abstract class Animal {
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Dog barks.";
}
}
$dog = new Dog();
$dog->makeSound();
?>
Sample Output
Dog barks.
Explanation
- The
abstractkeyword is used to declare an abstract class. - The
Animalclass contains an abstract method namedmakeSound(). - An abstract method has no method body.
- The
Dogclass inherits fromAnimalusingextends. - The
Dogclass must implement the abstract method.
You cannot create an object directly from an abstract class.
Concepts Covered
- Abstract classes
- Abstract methods
- The
extendskeyword - Implementing abstract methods
Question 2: Create an Abstract Class with Normal and Abstract Methods
Problem Statement
Create an abstract class named Employee with a normal method displayCompany() and an abstract method calculateSalary(). Create a child class named Manager that implements the abstract method.
PHP Solution
<?php
abstract class Employee {
public function displayCompany() {
echo "Company: ABC Technologies";
}
abstract public function calculateSalary();
}
class Manager extends Employee {
public function calculateSalary() {
echo "\nManager Salary: Rs. 60000";
}
}
$manager = new Manager();
$manager->displayCompany();
$manager->calculateSalary();
?>
Sample Output
Company: ABC Technologies
Manager Salary: Rs. 60000
Explanation
An abstract class can contain two types of methods:
- Normal method: Contains complete code and can be inherited directly.
- Abstract method: Contains only a declaration. The child class must provide its implementation.
The Manager class inherits displayCompany() and implements calculateSalary().
Concepts Covered
- Normal methods in abstract classes
- Abstract methods
- Inheritance
- Method implementation
Question 3: Create Multiple Child Classes from One Abstract Class
Problem Statement
Create an abstract class named Shape with an abstract method calculateArea(). Create two child classes, Rectangle and Circle, that calculate their areas differently.
PHP Solution
<?php
abstract class Shape {
abstract public function calculateArea();
}
class Rectangle extends Shape {
public function calculateArea() {
$length = 10;
$width = 5;
echo "Rectangle Area: " . ($length * $width);
}
}
class Circle extends Shape {
public function calculateArea() {
$radius = 7;
$pi = 3.14;
echo "Circle Area: " . ($pi * $radius * $radius);
}
}
$rectangle = new Rectangle();
$circle = new Circle();
$rectangle->calculateArea();
echo "\n";
$circle->calculateArea();
?>
Sample Output
Rectangle Area: 50
Circle Area: 153.86
Explanation
The Shape abstract class defines a common rule: every child class must provide a calculateArea() method.
Rectanglecalculates area using length multiplied by width.Circlecalculates area using π multiplied by radius squared.
Both classes follow the same rule but perform different calculations.
Concepts Covered
- Abstract class inheritance
- Multiple child classes
- Abstract method implementation
- Different calculations
Question 4: Create a Simple Interface
Problem Statement
Create an interface named Payment with a method pay(). Create a class named CashPayment that implements the interface and displays a payment confirmation message.
PHP Solution
<?php
interface Payment {
public function pay();
}
class CashPayment implements Payment {
public function pay() {
echo "Payment completed using Cash.";
}
}
$payment = new CashPayment();
$payment->pay();
?>
Sample Output
Payment completed using Cash.
Explanation
- The
interfacekeyword is used to create an interface. - The interface contains a method named
pay(). - The
implementskeyword connects a class to an interface. - The
CashPaymentclass must implement thepay()method.
An interface defines what a class must do, but the implementing class provides the actual method code.
Concepts Covered
- Interfaces
- The
implementskeyword - Interface methods
- Implementing a contract
Question 5: Implement One Interface in Multiple Classes
Problem Statement
Create an interface named Payment with a method processPayment(). Create two classes, CardPayment and UPIPayment, that implement the interface and display different payment messages.
PHP Solution
<?php
interface Payment {
public function processPayment();
}
class CardPayment implements Payment {
public function processPayment() {
echo "Payment completed using Debit Card.";
}
}
class UPIPayment implements Payment {
public function processPayment() {
echo "Payment completed using UPI.";
}
}
$card = new CardPayment();
$upi = new UPIPayment();
$card->processPayment();
echo "\n";
$upi->processPayment();
?>
Sample Output
Payment completed using Debit Card.
Payment completed using UPI.
Explanation
The Payment interface defines a common method named processPayment().
Both classes implement this interface, but each provides its own implementation.
CardPaymentprocesses a card payment.UPIPaymentprocesses a UPI payment.
This approach makes it easier to add new payment methods without changing the basic payment contract.
Concepts Covered
- One interface with multiple classes
- Interface implementation
- Common method structure
- Different implementations
Question 6: Create an Interface with Method Parameters
Problem Statement
Create an interface named Notification with a method sendMessage($message). Create two classes, EmailNotification and SMSNotification, that implement the interface and display the message differently.
PHP Solution
<?php
interface Notification {
public function sendMessage($message);
}
class EmailNotification implements Notification {
public function sendMessage($message) {
echo "Email Notification: " . $message;
}
}
class SMSNotification implements Notification {
public function sendMessage($message) {
echo "SMS Notification: " . $message;
}
}
$email = new EmailNotification();
$sms = new SMSNotification();
$email->sendMessage("Your order has been confirmed.");
echo "\n";
$sms->sendMessage("Your payment was successful.");
?>
Sample Output
Email Notification: Your order has been confirmed.
SMS Notification: Your payment was successful.
Explanation
The interface declares a method that accepts one parameter named $message.
Both implementing classes must provide a compatible method.
The same message can be delivered through different notification systems.
Concepts Covered
- Interface methods with parameters
- Method implementation
- Passing arguments
- Interface-based design
Question 7: Implement Multiple Interfaces in One Class
Problem Statement
Create two interfaces named Printable and Downloadable.
Printableshould contain a method namedprintDocument().Downloadableshould contain a method nameddownloadDocument().
Create a class named Document that implements both interfaces.
PHP Solution
<?php
interface Printable {
public function printDocument();
}
interface Downloadable {
public function downloadDocument();
}
class Document implements Printable, Downloadable {
public function printDocument() {
echo "Document is ready for printing.";
}
public function downloadDocument() {
echo "\nDocument downloaded successfully.";
}
}
$file = new Document();
$file->printDocument();
$file->downloadDocument();
?>
Sample Output
Document is ready for printing.
Document downloaded successfully.
Explanation
PHP allows one class to implement multiple interfaces.
In this example:
Printablerequires theprintDocument()method.Downloadablerequires thedownloadDocument()method.Documentimplements both interfaces.- Therefore, the class must provide both methods.
This is useful when one class needs to follow multiple sets of rules.
Concepts Covered
- Multiple interfaces
- Implementing multiple contracts
- Interface methods
- Class design
Question 8: Extend One Interface Using Another Interface
Problem Statement
Create an interface named BasicPayment with a method pay(). Create another interface named AdvancedPayment that extends BasicPayment and adds a method refund().
Create a class named OnlinePayment that implements AdvancedPayment.
PHP Solution
<?php
interface BasicPayment {
public function pay();
}
interface AdvancedPayment extends BasicPayment {
public function refund();
}
class OnlinePayment implements AdvancedPayment {
public function pay() {
echo "Online payment completed.";
}
public function refund() {
echo "\nPayment refunded successfully.";
}
}
$payment = new OnlinePayment();
$payment->pay();
$payment->refund();
?>
Sample Output
Online payment completed.
Payment refunded successfully.
Explanation
An interface can extend another interface using the extends keyword.
Here:
BasicPaymentdefines thepay()method.AdvancedPaymentinherits thepay()requirement and addsrefund().OnlinePaymentimplementsAdvancedPayment, so it must provide both methods.
Remember: interfaces extend interfaces, while classes implement interfaces.
Concepts Covered
- Interface inheritance
- Extending interfaces
- Implementing inherited methods
- Multiple method requirements
Question 9: Use an Abstract Class and an Interface Together
Problem Statement
Create an interface named Reportable with a method generateReport(). Create an abstract class named Employee that implements the interface and contains an abstract method calculateSalary().
Create a child class named Manager that implements both required methods.
PHP Solution
<?php
interface Reportable {
public function generateReport();
}
abstract class Employee implements Reportable {
abstract public function calculateSalary();
public function displayCompany() {
echo "Company: ABC Technologies";
}
}
class Manager extends Employee {
public function calculateSalary() {
echo "Salary: Rs. 60000\n";
}
public function generateReport() {
echo "Manager report generated.";
}
}
$manager = new Manager();
$manager->displayCompany();
echo "\n";
$manager->calculateSalary();
$manager->generateReport();
?>
Sample Output
Company: ABC Technologies
Salary: Rs. 60000
Manager report generated.
Explanation
This example combines abstract classes and interfaces.
Reportabledefines thegenerateReport()requirement.Employeeimplements the interface but remains abstract.Employeealso declares an abstract method namedcalculateSalary().Managerprovides implementations for both required methods.- The normal method
displayCompany()is inherited directly.
An abstract class can declare that it implements an interface while leaving some methods for its concrete child class to implement.
Concepts Covered
- Abstract classes and interfaces together
- Interface implementation by an abstract class
- Abstract methods
- Inheritance
Question 10: Build an Employee Management System Using an Interface
Problem Statement
Create an interface named SalaryCalculator with a method calculateSalary().
Create two classes:
Manager: Receives a fixed monthly salary of Rs. 60,000.Developer: Receives Rs. 500 per working hour and works 120 hours.
Store both objects in an array and calculate their salaries using a common interface method.
PHP Solution
<?php
interface SalaryCalculator {
public function calculateSalary();
}
class Manager implements SalaryCalculator {
public function calculateSalary() {
$salary = 60000;
echo "Manager Salary: Rs. " . $salary;
}
}
class Developer implements SalaryCalculator {
public function calculateSalary() {
$hours = 120;
$rate = 500;
$salary = $hours * $rate;
echo "Developer Salary: Rs. " . $salary;
}
}
$employees = [
new Manager(),
new Developer()
];
foreach ($employees as $employee) {
$employee->calculateSalary();
echo "\n";
}
?>
Sample Output
Manager Salary: Rs. 60000
Developer Salary: Rs. 60000
Explanation
This example demonstrates how interfaces can be used in a practical employee management system.
SalaryCalculatordefines a common salary calculation rule.ManagerandDeveloperimplement the interface.- Each class calculates salary using its own logic.
- Both objects are stored in one array.
- The loop calls the same method on each object.
PHP executes the correct implementation based on the actual object.
This makes the system easier to extend. For example, you can add a Designer class that implements the same interface without changing the existing salary calculation loop.
Concepts Covered
- Interface-based programming
- Multiple implementing classes
- Polymorphism through interfaces
- Array of objects
- Employee salary management
Key Takeaways
- An abstract class is a class that cannot be instantiated directly.
- An abstract class can contain both normal methods and abstract methods.
- An abstract method has no method body and must be implemented by a concrete child class.
- An interface defines a contract that implementing classes must follow.
- Use
extendswhen a class inherits from an abstract or regular class. - Use
implementswhen a class follows an interface. - A class can implement multiple interfaces.
- An interface can extend another interface.
- An abstract class can implement an interface and leave some method implementations to its child class.
- Interfaces and abstract classes help create organized, reusable, and maintainable PHP applications.
Frequently Asked Questions (FAQs)
1. What is an abstract class in PHP?
An abstract class is a class declared using the abstract keyword. It cannot be instantiated directly and is designed to be inherited by other classes.
2. What is an abstract method in PHP?
An abstract method is a method declared without a body. A concrete child class must provide its implementation.
3. Can we create an object of an abstract class?
No. PHP does not allow direct object creation from an abstract class. You must create an object of a concrete child class.
4. What is an interface in PHP?
An interface defines a contract that specifies which public methods an implementing class must provide.
5. What is the difference between an abstract class and an interface?
An abstract class can contain properties, constructors, normal methods, and abstract methods. An interface primarily defines method contracts and can also declare constants. Modern PHP interfaces can also declare properties through supported accessor contracts in newer versions, but not ordinary instance properties.
6. What is the difference between extends and implements?
extendsis used when a class inherits from another class or an interface extends another interface.implementsis used when a class follows an interface.
7. Can one class implement multiple interfaces in PHP?
Yes. A class can implement multiple interfaces by separating their names with commas.
8. Can an interface extend another interface?
Yes. An interface can extend one or more interfaces using the extends keyword.
9. Can an abstract class implement an interface?
Yes. An abstract class can implement an interface without providing every required method immediately. A concrete child class must complete the remaining implementations.
10. When should we use an abstract class instead of an interface?
Use an abstract class when related classes need to share common properties or existing method code. Use an interface when different classes need to follow the same method contract, even if they do not share a common parent class.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
