OOP Introduction
Object-oriented programming organises code into classes and objects.
Object-Oriented Programming (OOP) models real-world things as objects. It is built on two core ideas:
- A class is a blueprint or template.
- An object is a concrete instance created from that class.
OOP helps you group related data and behaviour together, making large programs easier to manage.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Model a web application's domain as classes (User, Order, Product) to keep related data and logic together.
- Replace a sprawling set of global functions with a class so the code can be instantiated and tested in isolation.
- Use OOP to build reusable library components that can be shared across multiple projects via Composer.
More examples
Procedural vs OOP comparison
Moving related data and functions into a class encapsulates them, reducing the chance of naming conflicts and improving cohesion.
<?php
// Procedural
function getUserName(array $user): string {
return $user['name'];
}
// OOP
class User {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function getName(): string {
return $this->name;
}
}
$user = new User('Alice');
echo $user->getName(); // AliceCreating multiple instances
Each new keyword creates an independent object instance; the class is the blueprint, the objects are the products.
<?php
class Product {
public function __construct(
public string $name,
public float $price
) {}
}
$widget = new Product('Widget', 9.99);
$gadget = new Product('Gadget', 24.99);
echo "{$widget->name}: {$widget->price}\n";
echo "{$gadget->name}: {$gadget->price}";Objects as function arguments
An Order object bundles its data and the logic that operates on it, removing the need to pass arrays everywhere.
<?php
class Order {
public array $items = [];
public function addItem(string $name, float $price): void {
$this->items[] = compact('name', 'price');
}
public function total(): float {
return array_sum(array_column($this->items, 'price'));
}
}
$order = new Order();
$order->addItem('Widget', 9.99);
$order->addItem('Gadget', 24.99);
echo number_format($order->total(), 2); // 34.98
Discussion