OOP Basics — PHP

OOP groups data and functions into objects. A class is a template, new makes an object from that template, and each object keeps its own properties (its…

So far you've stored a menu item as an array, ["name" => "Fried Rice", "price" => 15], and the functions that read it are somewhere else. The more dishes and functions you have, the easier it is for the two to get separated, until you can't tell which function goes with which data.

OOP (Object-Oriented Programming) groups data and the functions that work on it into one container. That container is called an object, and an object is made from a class. Picture the menu card template at Mrs. Tini's Stall. Every card has a name field and a price field, and the card can "read out" what is on it: "Fried Rice, $15". There is one template and many cards: Fried Rice, Iced Tea, Chicken Noodles. In code, the template is the class, and each printed card is an object. The fields on a card (name, price) are properties, the data that belongs to an object. What a card can do (read out what is on it) are methods, the functions an object runs.

Class: the template

This is the class Menu, the template for a menu card:

<?php
class Menu {
    public string $name;
    public int $price;
    public string $category = "food";

    public function info(): string {
        return "$this->name - \$$this->price";
    }
}

Object: what the template prints

This code makes two objects from the class Menu above:

$rice = new Menu();
$rice->name = "Fried Rice";
$rice->price = 15;

$tea = new Menu();
$tea->name = "Iced Tea";
$tea->price = 5;

$rice->name = "Special Fried Rice";

echo $rice->info() . "\n"; // Special Fried Rice - $15
echo $tea->name . "\n";    // Iced Tea
echo $rice->category;      // food

Constructor: fill the properties when the object is made

When you fill properties one by one after new, it is easy to forget one. A constructor is a special method named __construct (two underscores in front). It runs automatically as soon as new is called:

<?php
class Menu {
    public string $name;
    public int $price;

    public function __construct(string $name, int $price) {
        $this->name = $name;
        $this->price = $price;
    }

    public function info(): string {
        return "$this->name - \$$this->price";
    }
}

$rice = new Menu("Fried Rice", 15);
echo $rice->info(); // Fried Rice - $15

The arguments in new Menu("Fried Rice", 15) are sent to the parameters of __construct. Then $this->name = $name; copies the value of the parameter $name into the property $this->name. Since PHP 8 there is a shorter way, called constructor property promotion. Write public in front of a constructor parameter, and a property with that name is created and filled at the same time:

class Menu {
    public function __construct(
        public string $name,
        public int $price,
    ) {}

    public function info(): string {
        return "$this->name - \$$this->price";
    }
}

The result is exactly the same as the long version above.

public, private, and readonly

This class uses public, readonly and private together:

<?php
class Menu {
    public function __construct(
        public string $name,
        public readonly int $price,
        private int $stock,
    ) {}

    public function sell(int $portions): void {
        $this->stock -= $portions;
    }

    public function remaining(): int {
        return $this->stock;
    }
}

$rice = new Menu("Fried Rice", 15, 10);
$rice->sell(3);
echo $rice->remaining(); // 7

Another option in PHP 8.4: private(set). With private, $stock needs the method remaining() so its value can be read from outside. With asymmetric visibility (PHP 8.4), the rule for reading a property and the rule for changing it can differ: the property can be read from anywhere, but changed only from inside the class:

<?php
class Menu {
    public function __construct(
        public string $name,
        public private(set) int $stock,
    ) {}

    public function sell(int $portions): void {
        $this->stock -= $portions;
    }
}

$rice = new Menu("Fried Rice", 10);
$rice->sell(3);
echo $rice->stock . "\n"; // 7
$rice->stock = 99;        // Error: Cannot modify private(set) property Menu::$stock from global scope

In public private(set) int $stock, the public is for reading, and private(set) is for changing. PHP 8.4 also adds property hooks: get and set blocks written directly on a property. For example, a set block can refuse a negative price every time $price is set.

📌 static: belongs to the class, not an object

This class counts how many Menu objects have been made:

<?php
class Menu {
    public static int $count = 0;

    public function __construct(public string $name, public int $price) {
        self::$count++;
    }
}

$rice = new Menu("Fried Rice", 15);
$tea = new Menu("Iced Tea", 5);
echo Menu::$count; // 2

A normal property exists in every object. A static property exists only once, and all objects share it. Here each new Menu(...) adds 1 to self::$count, so the result is 2. Inside the class, a static property is read with self::$count, and from outside with Menu::$count. A normal method (not static), like info() in the earlier Menu class, needs an object. So Menu::info() is refused with Error: Non-static method Menu::info() cannot be called statically.

⚠️ What's easy to forget when making objects

TL;DR: OOP groups data and functions into objects. A class is a template, new makes an object from that template, and each object keeps its own properties (its data). -> is used to read an object's properties and call its methods (functions inside the class), and $this inside a method means the object running that method. __construct (the constructor) runs automatically on new. With constructor property promotion, public function __construct(public string $name) {} creates and fills the property at the same time. public can be reached from outside, private only from inside the class, and readonly is filled only once. static belongs to the class, not an object: self::$count inside the class, Menu::$count outside.

⚡ A class is a template

Write:

<?php
class Menu {
    public string $name;
    public int $price;

    public function info(): string {
        return "$this->name - \$$this->price";
    }
}

Meaning: A class is a template, and objects are made from it, like many menu cards made from one template. $name and $price are properties (the data of each object). info() is a method (a function inside the class). Inside a method, $this means the object running that method.

⚡ Each object keeps its own values

Write:

$rice = new Menu();
$rice->name = "Fried Rice";

$tea = new Menu();
$tea->name = "Iced Tea";

$rice->name = "Special Fried Rice";
Guess first: after the last line, what does $tea->name hold?

Still Iced Tea. Each object keeps its own values, so changing $rice->name doesn't touch any other object.

Meaning: new makes one new object from the class Menu. $rice->name means the property name of the object $rice.

⚡ The constructor fills it when the object is made

Write:

class Menu {
    public function __construct(
        public string $name,
        public int $price,
    ) {}
}

$rice = new Menu("Fried Rice", 15);

Meaning: __construct (the constructor) is a method that runs automatically as soon as new is called. The arguments "Fried Rice" and 15 go into its parameters. With public in front of a parameter, the properties $name and $price are created and filled at the same time.

What you will learn