Object-Oriented Programming (OOP) is a paradigm that organises code into objects — bundles of data (properties) and behaviour (methods).
// Procedural
function getArea($w, $h) { return $w * $h; }
echo getArea(5, 3); // 15
// OOP
class Rectangle {
public function __construct(
private float $width,
private float $height
) {}
public function area(): float {
return $this->width * $this->height;
}
}
$rect = new Rectangle(5, 3);
echo $rect->area(); // 15
class BankAccount {
private float $balance = 0;
public function __construct(private string $owner) {}
public function deposit(float $amount): void {
$this->balance += $amount;
}
public function getBalance(): float {
return $this->balance;
}
public function __toString(): string {
return "{$this->owner}: $" . number_format($this->balance, 2);
}
}
$account = new BankAccount("Alice");
$account->deposit(1000);
$account->deposit(250.50);
echo $account; // Alice: $1,250.50