Start · Sprachen · PHP · Referenz · Constructor Property Promotion

Constructor Property Promotion

Konzept

Verkürzt die Property-Deklaration und Konstruktor-Zuweisung zu einer einzigen Zeile.

seit PHP 8.0.0 Kategorie: oop

Signatur

public function __construct(public readonly string $name) {}

Beschreibung

Sichtbarkeits-Modifier (public, protected, private, readonly) im Konstruktor-Parameter deklarieren die Property automatisch.

Rückgabewert

Typ
void

Beispiele

Vorher / Nachher

<?php

// Alt
class Point {
    public float $x;
    public float $y;
    public function __construct(float $x, float $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

// Neu
class Point {
    public function __construct(
        public readonly float $x,
        public readonly float $y,
    ) {}
}