WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / PHP

Eigenschaften über Konstruktorparameter deklarieren

Ein Sichtbarkeitsmodifikator am Konstruktorparameter deklariert zugleich eine Eigenschaft (`Constructor property promotion`).

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

public function __construct(public string $name, private int $stock = 0) {}

Ein Sichtbarkeitsmodifikator am Konstruktorparameter deklariert zugleich eine Eigenschaft (Constructor property promotion). PHP weist ihr den Argumentwert vor Ausführung des Konstruktorrumpfs zu. Der Standardwert gehört zum Parameter. Ein gewöhnlicher Parameter deklariert kein Feld und eine promovierte Eigenschaft darf nicht erneut deklariert werden.

class Product {
    public int $initial;
    public function __construct(public string $name, private int $stock = 2, int $extra = 1) {
        $this->initial = $this->stock;
        $this->stock += $extra;
    }
    public function stock(): int { return $this->stock; }
}
$p = new Product("tea");
echo json_encode([$p->name, $p->initial, $p->stock(), property_exists($p, "extra")]);
["tea",2,3,false]

Beispiele

<?php
class Product {
    public int $initial;
    public function __construct(public string $name, private int $stock = 2, int $extra = 1) {
        $this->initial = $this->stock;
        $this->stock += $extra;
    }
    public function stock(): int { return $this->stock; }
}
$p = new Product("tea");
echo json_encode([$p->name, $p->initial, $p->stock(), property_exists($p, "extra")]);

Ergebnis

["tea",2,3,false]

Quellen