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";
}
}
class Menu { ... }creates a template namedMenu. Class names usually start with a capital letter.public string $name;is a property: a variable that belongs to each object, with its type.publicmeans this property can be read and changed from outside the class.- A property can have a starting value, like
$category = "food". Every new object holds that value right away. public function info()is a method: a function written inside the class. Inside a method,$thismeans "the object running this method". So$this->nameis the propertynameof that object itself.
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
new Menu()makes one new object from the classMenu.->is used to reach inside an object:$rice->namereads its property, and$rice->info()calls its method.- Each object keeps its own property values. Changing
$rice->namedoesn't touch$tea->name, so$tea->nameis stillIced Tea.
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
privatemeans only the methods inside that class may read or change the property. Here$stockcan only change through the methodsell(), which lowers it by$portions(-=means subtract).echo $rice->stock;from outside the class is refused:Error: Cannot access private property Menu::$stock.protectedis likeprivate, but child classes (other classes that inherit what is in this class) may use it too. You will seeprotectedin the Advanced OOP lesson.readonly(PHP 8.1) means the property is filled once in the constructor and can't be changed after that.$rice->price = 20;is refused:Error: Cannot modify readonly property Menu::$price.
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
- Forgetting
$this->inside a method.return "$name - \$$price";looks for local variables (variables created inside that method), not properties. The result isWarning: Undefined variable $name, and the text that comes out is just- $. - Forgetting
new.$rice = Menu("Fried Rice", 15);is taken as a function call:Error: Call to undefined function Menu(). - Mistyping a property name.
$rice->prcie = 20;quietly creates a new property. PHP 8.2 and later giveDeprecated: Creation of dynamic property Menu::$prcie is deprecated(deprecated means this way of writing code is outdated), and$rice->pricedoesn't change. - Changing a
readonlyproperty. Fill it through the constructor, once.
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.