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:
<?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();
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.
| Idea | In one sentence |
|---|---|
| Encapsulation | An object protects its own data and exposes only what is needed |
| Inheritance | A class can build on another class |
| Polymorphism | Different classes can be used through the same interface |
| Abstraction | Show 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.