PhPHP · Lesson 5 of 8

Classes & Modern OOP

PHP's object system is genuinely good now. Constructor property promotion, readonly properties, enums, interfaces — this is where modern PHP shines brightest.

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();
✦ Tip
Classes autoload by convention: one class per file, file path matches namespace (PSR-4 standard). You'll rarely write require statements — Composer (next lesson) generates the autoloader.