PHPPHP
IntermediateLesson 9 of 16

Classes, Interfaces & Traits – PHP

Object-oriented programming with constructor promotion, inheritance, interfaces and traits.

With constructor promotion (PHP 8) you declare properties directly in the constructor signature. private, protected and public control visibility; static and const belong to the class instead of the object.

<?php
declare(strict_types=1);

class Konto {
    public const WAEHRUNG = "EUR";
    private static int $anzahl = 0;
    private float $saldo = 0.0;

    public function __construct(private readonly string $inhaber) {
        self::$anzahl++;
    }
    public function einzahlen(float $betrag): static {
        $this->saldo += $betrag;
        return $this;
    }
    public static function anzahl(): int {
        return self::$anzahl;
    }
    public function __toString(): string {
        return sprintf("%s: %.2f %s", $this->inhaber, $this->saldo, self::WAEHRUNG);
    }
}

$k = (new Konto("Ada"))->einzahlen(50)->einzahlen(25.5);
echo $k, "\n";               // Ada: 75.50 EUR
echo Konto::anzahl(), "\n";  // 1

An interface defines which methods a class must have. An abstract class additionally provides shared code. With static::class you get the name of the actual class.

<?php
interface Form {
    public function flaeche(): float;
}
abstract class Basis implements Form {
    public function beschreibe(): string {
        return static::class . " with area " . round($this->flaeche(), 2);
    }
}
final class Kreis extends Basis {
    public function __construct(private float $r) {}
    public function flaeche(): float { return M_PI * $this->r ** 2; }
}
final class Rechteck extends Basis {
    public function __construct(private float $b, private float $h) {}
    public function flaeche(): float { return $this->b * $this->h; }
}
foreach ([new Kreis(1), new Rechteck(2, 3)] as $form) {
    echo $form->beschreibe(), "\n";   // Kreis with area 3.14 / Rechteck with area 6
}

Traits share code between classes that do not inherit from each other (PHP only has single inheritance):

<?php
trait Zeitstempel {
    private ?string $erstellt = null;
    public function markiere(): void { $this->erstellt = "2026-01-01"; }
    public function erstellt(): ?string { return $this->erstellt; }
}
class Artikel { use Zeitstempel; }
class Kommentar { use Zeitstempel; }

$a = new Artikel();
$a->markiere();
echo $a->erstellt(), "\n";   // 2026-01-01
WarningObjects are passed as a handle: $b = $a; does not create a copy, both point to the same object. You create a copy with clone $a.
TipPrefer composition and interfaces over deep inheritance, and mark classes as final if they are not meant to be extended.