Inheritance — extends
A child class gets everything from its parent and can add or change behaviour:
class User { ... }
class Teacher extends User { ... }
- Override a method by writing it again in the child
- Call the parent version with
parent::method() finalstops a class or method from being extended
Abstract classes
A base class that cannot be created directly. It can force children to write certain methods:
abstract class Payment {
abstract public function pay(float $amount): string;
}
Interfaces — a contract
Lists methods a class must have. A class can implement many interfaces:
interface Notifier { public function send(string $to, string $msg): bool; }
class SmsNotifier implements Notifier { ... }
Code can then accept any Notifier — SMS, email or WhatsApp — without changing.
Traits — reuse code
PHP allows only one parent class. Traits share methods across unrelated classes:
trait HasSlug { public function slug(): string { ... } }
class Course { use HasSlug; }
Laravel uses traits a lot: use HasFactory, Notifiable;.
Example
<?php
interface Refundable
{
public function refund(float $amount): string;
}
trait LogsActivity
{
public function log(string $message): void
{
echo '[' . date('H:i') . '] ' . static::class . ": $message<br>";
}
}
abstract class Payment
{
use LogsActivity;
public function __construct(protected string $customer) {}
abstract public function pay(float $amount): string;
protected function rupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}
}
class UpiPayment extends Payment implements Refundable
{
public function __construct(string $customer, private string $upiId)
{
parent::__construct($customer);
}
public function pay(float $amount): string
{
$this->log("paying {$this->rupees($amount)}");
return "{$this->customer} paid {$this->rupees($amount)} via UPI ({$this->upiId})";
}
public function refund(float $amount): string
{
return "Refunded {$this->rupees($amount)} to {$this->upiId}";
}
}
class CashPayment extends Payment
{
public function pay(float $amount): string
{
$this->log('cash received');
return "{$this->customer} paid {$this->rupees($amount)} in cash";
}
}
$payments = [new UpiPayment('Asha', 'asha@upi'), new CashPayment('Ravi')];
foreach ($payments as $p) {
echo $p->pay(1499) . '<br>';
if ($p instanceof Refundable) {
echo $p->refund(200) . '<br>';
}
}
Output: a log line and "Asha paid ₹1,499.00 via UPI (asha@upi)", "Refunded ₹200.00 to asha@upi", then a log line and "Ravi paid ₹1,499.00 in cash".