- Write a class with properties and methods and create objects with
new - Apply constructor promotion,
readonlyand visibility levels - Use static members and inheritance with
extends
A bank account has an owner and a balance; you can deposit money and check the balance. To keep data and the functions that work with it in one place, we use object-oriented programming (OOP). Modern PHP frameworks such as Laravel and Symfony are built entirely on classes, so this topic is the foundation of professional PHP work.
Class and object
A class is a blueprint for objects: it describes which properties (data) and methods (actions) they will have. An object is a concrete instance of a class created with new. Inside a method, $this refers to the current object, and properties and methods are accessed with the -> operator. The __construct method is called automatically when an object is created.
<?php
class Account
{
public string $owner;
private float $balance = 0.0;
public function __construct(string $owner)
{
$this->owner = $owner;
}
public function deposit(float $amount): void
{
$this->balance += $amount;
}
public function getBalance(): float
{
return $this->balance;
}
}
$acc = new Account("Aysel");
$acc->deposit(50);
$acc->deposit(25.5);
echo $acc->owner, ": ", $acc->getBalance(), " AZN\n";Aysel: 75.5 AZN
| Visibility | Accessible from |
|---|---|
public | everywhere |
protected | the class itself and its child classes |
private | only the class itself |
$acc->balance, you get a Cannot access private property error — the balance changes only through methods.Constructor promotion and readonly
In the class above, $owner is written three times: as a property, a parameter and an assignment. With PHP 8's constructor promotion, you put the visibility right on the constructor parameter — PHP declares the property and assigns the value for you.
class Product
{
private string $name;
private float $price;
public function __construct(string $name, float $price)
{
$this->name = $name;
$this->price = $price;
}
}class Product
{
public function __construct(
private string $name,
private float $price,
) {}
}Since PHP 8.1 a property can be declared readonly: it gets a value only once, inside the class. If you try to change it later, you get the error Cannot modify readonly property Money::$amount. Such immutable objects are ideal for values like money, dates and coordinates. Below we store money in qəpik (the manat’s cents) as an integer: 1 manat = 100 qəpik.
<?php
final class Money
{
public function __construct(
public readonly int $amount,
public readonly string $currency = "AZN",
) {}
public function add(Money $other): Money
{
return new Money($this->amount + $other->amount, $this->currency);
}
public function __toString(): string
{
return number_format($this->amount / 100, 2) . " " . $this->currency;
}
}
$price = new Money(1250);
$total = $price->add(new Money(799));
echo $total, "\n";
echo $total->amount, "\n";20.49 AZN 2049
adddoes not change the old object; it returns a newMoneyobject — that is how immutable objects work.- The special
__toStringmethod turns the object into a string, which is whyecho $totalworks. finalforbids creating child classes from this class.
Static members
Static properties and methods belong to the whole class, not to a single object. You access them with ClassName::member, and from inside the class with self::. Class constants (const) are read the same way. Below, the class counts how many student objects have been created.
<?php
class Student
{
public const MAX_IN_CLASS = 30;
private static int $count = 0;
public function __construct(public string $name)
{
self::$count++;
}
public static function count(): int
{
return self::$count;
}
}
new Student("Leyla");
new Student("Murad");
$s = new Student("Nigar");
echo Student::count(), " of ", Student::MAX_IN_CLASS, "\n";
echo $s->name, "\n";3 of 30 Nigar
Inheritance
With the extends keyword a class inherits all the public and protected members of another class and can override any of its methods. The parent's method is reached with parent::. In PHP a class can have only one parent. When the same method behaves differently in different classes, it is called polymorphism.
<?php
class Animal
{
public function __construct(protected string $name) {}
public function speak(): string
{
return "{$this->name} makes a sound";
}
}
class Cat extends Animal
{
public function speak(): string
{
return "{$this->name} says Meow";
}
}
class Dog extends Animal
{
public function speak(): string
{
return parent::speak() . ": Woof!";
}
}
$pets = [new Animal("Fish"), new Cat("Mestan"), new Dog("Bobik")];
foreach ($pets as $pet) {
echo $pet->speak(), "\n";
}Fish makes a sound Mestan says Meow Bobik makes a sound: Woof!
Key points
- A class is a blueprint and an object is an instance created with
new;$thismeans the current object and->accesses a member. public,protectedandprivatedecide where members are visible; keep dataprivateand change it through methods.- Constructor promotion (PHP 8) declares properties in the constructor parameters;
readonly(PHP 8.1) makes a property immutable. - Static members belong to the class and are read with
self::orClassName::. extendscreates inheritance,parent::calls the parent's method, andfinalforbids inheritance.
Check yourself
10 questions. Every correct answer earns XP.
$this refer to inside a method?