PHPPHP
FortgeschrittenLektion 9 von 16

Klassen, Interfaces & Traits – PHP

Objektorientierung mit Constructor Promotion, Vererbung, Interfaces und Traits.

Mit Constructor Promotion (PHP 8) deklarierst du Eigenschaften direkt in der Konstruktor-Signatur. private, protected und public steuern die Sichtbarkeit; static und const gehören zur Klasse statt zum Objekt.

<?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

Ein Interface legt fest, welche Methoden eine Klasse haben muss. Eine abstrakte Klasse liefert zusätzlich gemeinsamen Code. Mit static::class erhältst du den Namen der tatsächlichen Klasse.

<?php
interface Form {
    public function flaeche(): float;
}
abstract class Basis implements Form {
    public function beschreibe(): string {
        return static::class . " mit Fläche " . 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 mit Fläche 3.14 / Rechteck mit Fläche 6
}

Traits teilen Code zwischen Klassen, die nicht voneinander erben (PHP kennt nur Einfachvererbung):

<?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
AchtungObjekte werden als Handle übergeben: $b = $a; erzeugt keine Kopie, beide zeigen auf dasselbe Objekt. Eine Kopie erstellst du mit clone $a.
TippBevorzuge Komposition und Interfaces vor tiefer Vererbung, und markiere Klassen als final, wenn sie nicht zum Erweitern gedacht sind.