Skip to content

PHP Tutorial Object-Oriented PHP

What Is Object-Oriented Programming?

Lesson 197 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

So far you have written code as a list of steps, with variables and functions. That style is called procedural programming, and it works well for small scripts.

As a project grows, you find yourself passing the same group of values around: a user’s name, email, role and ID. Object-oriented programming (OOP) keeps related data and the code that works on it together in one unit, called an object.

A picture: a car

A real car has:

  • Properties (data): colour, speed, fuel level.
  • Actions (behaviour): accelerate, brake, refuel.

An object in code is the same: it has properties and methods.

Procedural vs object-oriented

The same small task in two styles:

index.php
PHP
<?php
// Procedural: data and functions are separate
$user = ["name" => "Isha", "email" => "isha@example.com"];

function greetUser(array $user): string
{
    return "Hello, " . $user["name"];
}

echo greetUser($user) . "\n";

// Object-oriented: data and behaviour live together
class User
{
    public function __construct(
        public string $name,
        public string $email,
    ) {}

    public function greet(): string
    {
        return "Hello, " . $this->name;
    }
}

$user = new User("Isha", "isha@example.com");

echo $user->greet();
Output
OUTPUT
Hello, Isha
Hello, Isha

The result is the same. The difference shows when the project grows: a User always has a name and an email, and everything you can do with a user is in one place.

The four ideas of OOP

You will meet these in the next lessons.

IdeaIn one sentence
EncapsulationAn object protects its own data and exposes only what is needed
InheritanceA class can build on another class
PolymorphismDifferent classes can be used through the same interface
AbstractionShow what something does, hide how

Why use OOP

  • Organisation. Code is split into small, named pieces.
  • Reuse. One class can be used in many places.
  • Safety. Objects can protect their data and keep it valid.
  • Teamwork. Frameworks and libraries are built from classes, so you need OOP to use them.

When not to use it

A ten-line script does not need a class. OOP is a tool for managing complexity. Use it when you have something with a clear identity and several related actions, such as a user, an order, a product or a database connection.

Where you will meet it

  • Laravel and Symfony are built entirely from classes.
  • WordPress uses classes in many places (WP_Query, WP_Post, widgets).
  • Composer packages are almost always classes.
info
Why this matters in Laravel
Controllers, models, middleware and services in Laravel are all classes. Once you are comfortable with classes and objects, reading a Laravel project becomes much easier.