Lesson 5 of 8

Classes & Modern OOP

Learn to write classes in modern PHP, with constructor promotion, readonly properties, and enums.

PHP
<?php
declare(strict_types=1);

class Student
{
    // Constructor property promotion (PHP 8):
    // declares + assigns the properties in one place.
    public function __construct(
        public readonly string $name,
        private int $grade = 0,
    ) {}

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

    public function setGrade(int $grade): void
    {
        if ($grade < 0 || $grade > 100) {
            throw new InvalidArgumentException("Grade out of range");
        }
        $this->grade = $grade;
    }
}

$ada = new Student("Ada", 95);
echo $ada->name;         // Ada  (-> accesses members)
$ada->name = "Bob";      // Error: readonly property
PHP
<?php
interface Shape
{
    public function area(): float;
}

class Circle implements Shape
{
    public function __construct(private float $radius) {}

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

// Enums (PHP 8.1) — real enums, with methods:
enum Status: string
{
    case Active    = 'active';
    case Suspended = 'suspended';

    public function label(): string
    {
        return match($this) {
            Status::Active    => 'Active student',
            Status::Suspended => 'Suspended',
        };
    }
}

$s = Status::from('active');
echo $s->label();
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.