Object-Oriented PHP: Code You Can Still Read Later From a Pile of Functions to a Class
1 / 5
Next
From a Pile of Functions to a Class ~16min

The problem OOP solves

Six functions that all take $pdo and a user id, plus three globals nobody dares remove. It works until someone else has to change it.

A class bundles data with the things that act on it

class Order
{
    public function __construct(
        private PDO $pdo,
        private int $id
    ) {}

    public function total(): float
    {
        $stmt = $this->pdo->prepare("SELECT SUM(qty * unit_price) FROM order_items WHERE order_id = ?");
        $stmt->execute([$this->id]);
        return (float)$stmt->fetchColumn();
    }
}
$order = new Order($pdo, 24);
echo $order->total();

Constructor property promotion

Declaring the properties in the constructor signature (as above) is PHP 8 shorthand. It replaces three lines of boilerplate per property, and it is now the normal style.

$this

Inside a class, $this means "this particular object". Two Order objects have separate $id values and never interfere.

When NOT to reach for a class

One function used once does not need one. OOP earns its keep when state and behaviour belong together and get reused, not as a rule to apply everywhere.

Tasks
Preview