Classes, enums and readonly

Classes with constructor promotion, readonly properties, interfaces and enums.

Runs in Zerethon IDE · PHP 8.4 Official PHP documentation ↗
main.php
<?php

enum Suit: string
{
    case Hearts = 'H';
    case Spades = 'S';

    public function color(): string
    {
        return $this === self::Hearts ? 'red' : 'black';
    }
}

final class Point
{
    public function __construct(
        public readonly int $x,
        public readonly int $y,
    ) {}

    public function distance(): float
    {
        return sqrt($this->x ** 2 + $this->y ** 2);
    }
}

$p = new Point(3, 4);
echo $p->x, ' ', $p->distance(), "\n";
echo Suit::from('H')->name, ' ', Suit::Spades->color(), "\n";

Output

3 5
Hearts black
  • Constructor promotion (public readonly int $x in the constructor) declares and assigns the property in one place.
  • A readonly property can be set once; changing it later throws an Error.
  • Call methods with ->, static members with ::.