Object-Oriented Programming (OOP) groups data and the functions that work on it into classes. Laravel and every modern PHP framework are built with OOP.
- A class is a blueprint (e.g.
Student) - An object is one thing made from it (
$asha = new Student(...))
Class example
class Student
{
public function __construct(
public string $name,
private int $marks = 0,
) {}
public function result(): string
{
return $this->marks >= 33 ? 'Pass' : 'Fail';
}
}
__construct()runs when you writenew Student(...)- Constructor property promotion (PHP 8) declares and sets properties in one line
$thismeans "this object"; use->to access properties and methods
Visibility
| Keyword | Accessible from |
|---|---|
public |
anywhere |
protected |
the class and its children |
private |
only the class itself |
Keep data private and expose methods — this is encapsulation.
Static and constants
public const PASS_MARK = 33; → Student::PASS_MARK. Static methods belong to the class: Student::create(...).
readonly (PHP 8.1)
public readonly string $roll; can be set once and never changed.
Example
Example — Bank account class
PHP
<?php
class BankAccount
{
public const MIN_BALANCE = 500;
private static int $count = 0;
public function __construct(
public readonly string $holder,
private float $balance = 0,
) {
self::$count++;
}
public function deposit(float $amount): static
{
$this->balance += $amount;
return $this;
}
public function withdraw(float $amount): static
{
if ($this->balance - $amount < self::MIN_BALANCE) {
throw new Exception('Minimum balance of ₹' . self::MIN_BALANCE . ' required.');
}
$this->balance -= $amount;
return $this;
}
public function balance(): string
{
return '₹' . number_format($this->balance, 2);
}
public static function total(): int
{
return self::$count;
}
}
$asha = new BankAccount('Asha', 1000);
$asha->deposit(2500)->withdraw(800);
echo "{$asha->holder}: {$asha->balance()}<br>";
$ravi = new BankAccount('Ravi');
try {
$ravi->withdraw(100);
} catch (Exception $e) {
echo 'Ravi: ' . $e->getMessage() . '<br>';
}
echo 'Accounts opened: ' . BankAccount::total();
Output: Asha: ₹2,700.00 / Ravi: Minimum balance of ₹500 required. / Accounts opened: 2