Skip to content
Educora
Intermediate18 min6 / 10

Classes and objects

Create classes, use constructor promotion and readonly properties, and learn static members and inheritance.

Check yourself
In this lesson you will learn
  • Write a class with properties and methods and create objects with new
  • Apply constructor promotion, readonly and 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
<?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";
Expected output
Aysel: 75.5 AZN
VisibilityAccessible from
publiceverywhere
protectedthe class itself and its child classes
privateonly the class itself
If you write $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.

PHP 7 style
class Product
{
    private string $name;
    private float $price;

    public function __construct(string $name, float $price)
    {
        $this->name = $name;
        $this->price = $price;
    }
}
PHP 8: constructor promotion
class Product
{
    public function __construct(
        private string $name,
        private float $price,
    ) {}
}
Both classes do exactly the same, but the one on the right is half as long.

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
<?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";
Expected output
20.49 AZN
2049
  • add does not change the old object; it returns a new Money object — that is how immutable objects work.
  • The special __toString method turns the object into a string, which is why echo $total works.
  • final forbids 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
<?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";
Expected output
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
<?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";
}
Expected output
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; $this means the current object and -> accesses a member.
  • public, protected and private decide where members are visible; keep data private and 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:: or ClassName::.
  • extends creates inheritance, parent:: calls the parent's method, and final forbids inheritance.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
What does $this refer to inside a method?