PHP interfaces and traits help developers create reusable, organized, and maintainable applications. An interface defines methods that a class must implement, while a trait allows methods to be reused across multiple classes.
An interface defines a contract that implementing classes must follow. It declares public method signatures without providing their implementation.
Use the interface keyword to create an
interface and implements to implement it.
<?php
interface Animal {
public function makeSound(): void;
}
class Dog implements Animal {
public function makeSound(): void {
echo "Dog barks.";
}
}
$dog = new Dog();
$dog->makeSound();
?>
Output:
Dog barks.
The Dog class must implement the
makeSound() method declared in the
Animal interface.
A class implements an interface using the
implements keyword. The class must provide
compatible implementations of all required methods.
<?php
interface Payment {
public function pay(float $amount): void;
}
class CashPayment implements Payment {
public function pay(float $amount): void {
echo "Paid Rs. " . number_format($amount, 2)
. " using cash.";
}
}
$payment = new CashPayment();
$payment->pay(1500);
?>
Output:
Paid Rs. 1,500.00 using cash.
The CashPayment class follows the contract
defined by the Payment interface.
Interfaces are useful when multiple classes should provide the same operations but implement them differently.
A PHP class can implement multiple interfaces by separating their names with commas.
<?php
interface Printable {
public function printDetails(): void;
}
interface Exportable {
public function exportData(): void;
}
class Report implements Printable, Exportable {
public function printDetails(): void {
echo "Displaying report details.<br>";
}
public function exportData(): void {
echo "Exporting report data.";
}
}
$report = new Report();
$report->printDetails();
$report->exportData();
?>
Output:
Displaying report details.
Exporting report data.
The Report class implements both interfaces
and must provide both required methods.
Unlike classes, which cannot directly extend multiple parent classes, PHP allows a class to implement multiple interfaces.
A trait is a mechanism for reusing methods across multiple classes without requiring those classes to inherit from the same parent class.
Use the trait keyword to define a trait
and use inside a class to include it.
<?php
trait Message {
public function showMessage(): void {
echo "Welcome to PHP Traits.";
}
}
class Student {
use Message;
}
$student = new Student();
$student->showMessage();
?>
Output:
Welcome to PHP Traits.
The Student class can use the
showMessage() method provided by the
Message trait.
Traits are especially helpful when unrelated classes need to share the same behavior.
A trait can be reused by multiple classes. Each class can use the trait's methods without duplicating their code.
<?php
trait Logger {
public function logMessage(string $message): void {
echo "Log: " . $message . "<br>";
}
}
class StudentManager {
use Logger;
public function addStudent(): void {
$this->logMessage("Student added.");
}
}
class FeeManager {
use Logger;
public function recordPayment(): void {
$this->logMessage("Payment recorded.");
}
}
$studentManager = new StudentManager();
$feeManager = new FeeManager();
$studentManager->addStudent();
$feeManager->recordPayment();
?>
Output:
Log: Student added.
Log: Payment recorded.
Both classes reuse the logging method from the
Logger trait.
This example prints log messages for learning purposes. Production applications should generally use a proper logging system instead of displaying logs to visitors.
Traits can contain properties and methods. A class that uses a trait receives those members, subject to PHP's trait compatibility rules.
<?php
trait Timestamp {
public function getCurrentDate(): string {
return date("Y-m-d");
}
public function getCurrentTime(): string {
return date("H:i:s");
}
}
class Attendance {
use Timestamp;
public function showAttendanceTime(): void {
echo "Date: " . $this->getCurrentDate() . "<br>";
echo "Time: " . $this->getCurrentTime();
}
}
$attendance = new Attendance();
$attendance->showAttendanceTime();
?>
Example output:
Date: 2026-10-15
Time: 10:30:45
The date and time shown in your actual output will depend on the server's configured time zone and the time when the script runs.
The Attendance class reuses both methods
from the Timestamp trait.
If two traits provide methods with the same name, PHP requires you to resolve the conflict when using both traits in the same class.
The insteadof keyword selects which
trait's method should be used.
<?php
trait FirstMessage {
public function show(): void {
echo "Message from FirstMessage.";
}
}
trait SecondMessage {
public function show(): void {
echo "Message from SecondMessage.";
}
}
class Demo {
use FirstMessage, SecondMessage {
FirstMessage::show insteadof SecondMessage;
SecondMessage::show as showSecond;
}
}
$obj = new Demo();
$obj->show();
echo "<br>";
$obj->showSecond();
?>
Output:
Message from FirstMessage.
Message from SecondMessage.
The insteadof keyword selects the preferred
implementation, while as creates an
additional alias for another trait method.
Interfaces and traits serve different purposes in object-oriented PHP.
| Feature | Interface | Trait |
|---|---|---|
| Purpose | Defines a contract | Reuses implementation |
| Keyword | interface | trait |
| Used by a class | implements | use |
| Method implementation | Ordinary interface methods declare requirements | Can provide method implementations |
| Multiple use | A class can implement multiple interfaces | A class can use multiple traits |
Interface example:
<?php
interface Notifier {
public function send(string $message): void;
}
class EmailNotifier implements Notifier {
public function send(string $message): void {
echo "Email: " . $message;
}
}
?>
Trait example:
<?php
trait Greeting {
public function greet(): void {
echo "Hello Student!";
}
}
class Student {
use Greeting;
}
?>
Use an interface when classes must follow a common contract. Use a trait when classes need to reuse existing implementation.
This example combines an interface and a trait. The interface defines a payment contract, while the trait provides reusable receipt formatting.
<?php
interface PaymentMethod {
public function pay(float $amount): void;
}
trait Receipt {
protected function showReceipt(
string $method,
float $amount
): void {
echo "Payment Method: " . $method . "<br>";
echo "Amount: Rs. " .
number_format($amount, 2) . "<br>";
echo "Payment processed successfully.<br>";
}
}
class CashPayment implements PaymentMethod {
use Receipt;
public function pay(float $amount): void {
if ($amount <= 0) {
throw new InvalidArgumentException(
"Payment amount must be positive."
);
}
$this->showReceipt("Cash", $amount);
}
}
class UpiPayment implements PaymentMethod {
use Receipt;
public function pay(float $amount): void {
if ($amount <= 0) {
throw new InvalidArgumentException(
"Payment amount must be positive."
);
}
$this->showReceipt("UPI", $amount);
}
}
try {
$cash = new CashPayment();
$cash->pay(1000);
echo "<hr>";
$upi = new UpiPayment();
$upi->pay(2500);
} catch (InvalidArgumentException $e) {
echo htmlspecialchars(
$e->getMessage(),
ENT_QUOTES | ENT_SUBSTITUTE,
"UTF-8"
);
}
?>
Output:
Payment Method: Cash
Amount: Rs. 1,000.00
Payment processed successfully.
Payment Method: UPI
Amount: Rs. 2,500.00
Payment processed successfully.
Both payment classes implement the same interface and reuse the receipt method from the trait.
This is a demonstration of OOP structure only. A real payment application must verify transactions through the appropriate payment provider before marking a payment as successful.
1. Which keyword is used to declare an interface?
2. Which keyword allows a class to reuse a trait?
3. What is the main purpose of an interface?