PHP What is OOP

JA JASWANT Updated 19 Oct 2026
6 min read ·Lesson 122 of 143
In this post

What Is Object-Oriented Programming? In simple terms: Object-oriented programming (OOP) organizes code around objects — units that combine data (what something is ) with behavior (what it can do ). A

What Is Object-Oriented Programming?

In simple terms: Object-oriented programming (OOP) organizes code around objects — units that combine data (what something is) with behavior (what it can do). A bank account object knows its balance and knows how to accept deposits and withdrawals; a shopping cart object knows its items and how to calculate its total.

Technically: In OOP, you define classes — blueprints that describe the properties (data) and methods (functions) of a kind of thing — and create objects (instances) from them. PHP has supported OOP since PHP 5 and has steadily added modern features: typed properties, constructor promotion, enums, readonly properties, and property hooks (PHP 8.4).

Procedural vs Object-Oriented

So far, most examples in this tutorial used procedural code: data in variables and arrays, processed by separate functions. That works well for small scripts. As applications grow, OOP helps keep code organized:

ProceduralObject-Oriented
Data (arrays) and functions are separateData and the functions that operate on it are combined
Any code can change any dataObjects control access to their own data
Related functions are grouped by naming conventionsRelated behavior lives in one class
Reuse by copying or calling functionsReuse through composition, inheritance, and interfaces
Good for small scriptsGood for larger, long-lived applications

A Comparison: Bank Account

Procedural Version

<?php
$account = ['owner' => 'Asha', 'balance' => 1000.0];

function deposit(array $account, float $amount): array
{
    $account['balance'] += $amount;
    return $account;
}

$account = deposit($account, 500);
$account['balance'] = -999999;   // nothing prevents this

echo $account['balance'] . "\n";

Output

-999999

The rules for a valid account (no negative deposits, no overdrafts) live in functions, but any code can bypass them and change the array directly. As a project grows, such changes happen in many places, and nobody can guarantee that the data is valid.

Object-Oriented Version

<?php
class BankAccount
{
    private float $balance = 0.0;

    public function __construct(private string $owner) {}

    public function deposit(float $amount): void
    {
        if ($amount <= 0) {
            throw new InvalidArgumentException('Deposit must be positive.');
        }
        $this->balance += $amount;
    }

    public function withdraw(float $amount): void
    {
        if ($amount > $this->balance) {
            throw new RuntimeException('Insufficient balance.');
        }
        $this->balance -= $amount;
    }

    public function balance(): float
    {
        return $this->balance;
    }
}

$account = new BankAccount('Asha');
$account->deposit(1000);
$account->withdraw(300);

echo "Balance: " . $account->balance() . "\n";

try {
    $account->withdraw(5000);
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

try {
    $account->balance = -999999;
} catch (Error $e) {
    echo get_class($e) . ": " . $e->getMessage() . "\n";
}

Output

Balance: 700
Error: Insufficient balance.
Error: Cannot access private property BankAccount::$balance

What Changed

  1. The balance is private: only the class's own methods can change it. Direct access from outside is rejected with an Error.
  2. All rules live in one place — deposit() and withdraw() — and are applied every time.
  3. Code using the class does not need to know how the balance is stored; it only uses the public methods.

This idea — protecting data behind methods that enforce the rules — is called encapsulation, and it is the most important benefit of OOP.


The Core Concepts

ConceptMeaningCovered In
ClassA blueprint that defines properties and methodsPHP Classes/Objects
ObjectAn instance of a class with its own dataPHP Classes/Objects
PropertyA variable that belongs to an objectPHP Properties
MethodA function that belongs to a classPHP Methods
ConstructorA method that initializes a new objectPHP Constructor

The Four Principles of OOP

PrincipleIdeaExample
EncapsulationHide internal data; expose a controlled public interfaceA private balance changed only via deposit() and withdraw()
AbstractionShow what an object does, hide how$mailer->send($email) without knowing SMTP details
InheritanceA class reuses and extends another classSavingsAccount extends BankAccount
PolymorphismDifferent classes can be used through the same interfaceEvery PaymentGateway has charge(), whether it is Razorpay or Stripe

Polymorphism in a Nutshell

<?php
interface Shape
{
    public function name(): string;
    public function area(): float;
}

class Circle implements Shape
{
    public function __construct(private float $radius) {}

    public function name(): string
    {
        return 'Circle';
    }

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

class Rectangle implements Shape
{
    public function __construct(private float $width, private float $height) {}

    public function name(): string
    {
        return 'Rectangle';
    }

    public function area(): float
    {
        return $this->width * $this->height;
    }
}

$shapes = [new Circle(2), new Rectangle(3, 4)];

foreach ($shapes as $shape) {
    echo $shape->name() . ': ' . number_format($shape->area(), 2) . "\n";
}

Output

Circle: 12.57
Rectangle: 12.00

Why This Is Powerful

  • The loop does not care which kind of shape it has; it only relies on the Shape interface.
  • Adding a new shape (a triangle, for example) requires a new class, but no change to the loop.
  • In real applications, the same idea lets you swap a payment provider, a storage system, or a mail service without changing the code that uses it.

Interfaces and polymorphism are covered in PHP Interfaces and Polymorphism.


Benefits of OOP

BenefitHow OOP Provides It
MaintainabilityRelated data and behavior are kept together, so changes are made in one place
Data integrityEncapsulation prevents invalid states
ReusabilityClasses can be reused across projects and composed into larger systems
TestabilityObjects with clear interfaces can be tested in isolation, and dependencies can be replaced with test doubles
CollaborationTeams can work on separate classes with well-defined interfaces
EcosystemFrameworks (Laravel, Symfony) and Composer packages are object-oriented

When Procedural Code Is Fine

OOP is not required for everything. Short scripts, simple command-line tools, and small one-page features are often clearer as a few functions. Use OOP when data has rules that must always be enforced, when the code base grows, or when different implementations of the same behavior are needed.


OOP in Real PHP Applications

In a typical Laravel or Symfony application, almost everything is an object:

ObjectResponsibility
Request / ResponseRepresent the HTTP request and response
ControllersHandle requests and choose responses
Models / Entities (Order, User)Represent business data and rules
Services (PaymentService, InvoiceGenerator)Perform business operations
RepositoriesLoad and save objects in the database
Value objects (Money, EmailAddress)Represent small, validated values

Learning OOP concepts is therefore essential for working with modern PHP frameworks and libraries.


Common Misconceptions

"OOP Means Putting Functions Into Classes"

Grouping unrelated static functions in a class (Utils::doEverything()) is still procedural code. OOP is about objects that own their data and enforce their rules.

"Everything Should Use Inheritance"

Deep inheritance hierarchies make code rigid. Modern design prefers composition (objects using other objects) and interfaces; inheritance is used where a true "is-a" relationship exists.

"OOP Is Slower"

The performance difference is negligible for web applications. The maintainability gains far outweigh it.


Best Practices

  • Model important concepts of your application as classes with clear responsibilities.
  • Keep data private and expose behavior through public methods.
  • Depend on interfaces rather than concrete classes where implementations may vary.
  • Prefer composition over deep inheritance.
  • Use procedural code where it is simpler; use OOP where structure and rules matter.

Official reference: https://www.php.net/manual/en/language.oop5.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning
Ask about this post
AI Ask about this post

Ask questions about PHP What is OOP and get answers drawn from it.

Signed-in readers only.