Object-Oriented Programming (OOP) organizes PHP code around objects that bundle related data (properties) and behavior (methods) into reusable blueprints called classes. While small scripts work fine with standalone functions, OOP keeps growing applications modular, predictable, and easy to test.
In procedural code, arrays and helper functions float separately across files, making it easy for mismatched keys or invalid state to creep in. OOP groups state and validation inside a single object boundary.
flowchart LR
C["Class Blueprint: Invoice"] --> O1["Object 1: Invoice #101 ($49)"]
C --> O2["Object 2: Invoice #102 ($120)"]
O1 --> M["Shared Methods: addItem(), markPaid()"]
O2 --> M
Every major PHP framework—including Laravel and Symfony—relies on four practical OOP ideas:
private or protected and expose safe methods that enforce business rules.interface contracts.extends.<?php
declare(strict_types=1);
class BankAccount
{
public function __construct(
private string $owner,
private float $balance = 0.0
) {}
public function deposit(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException('Deposit must be positive.');
}
$this->balance += $amount;
}
public function summary(): string
{
return "{$this->owner}: $" . number_format($this->balance, 2);
}
}
$account = new BankAccount('Tariq', 100.0);
$account->deposit(45.50);
echo $account->summary() . PHP_EOL;
public: Public properties allow external code to set invalid states like $account->balance = -999. Protect invariants behind methods.User class.declare(strict_types=1);: Typed class properties and constructor parameters prevent subtle type mismatches across objects.No. Simple CLI scripts, config files, and tiny utilities are often cleaner as small functions. OOP shines as soon as your app manages domain models, services, and multiple collaborators.
A DTO is a lightweight class (often using PHP 8.2 readonly properties) whose only job is carrying typed structured data between layers like controllers and services.
Under PSR-4, placing class InvoiceService in app/Services/InvoiceService.php under namespace App\Services; lets Composer load the file automatically whenever you reference it.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.