PHP8: Constructor Property Promotion

28.11.2022 | PHP

When a method parameter is prefixed with one of the visibility keywords public, protected or private, it is considered to be “promoted”. For each promoted parameter, a property with the same name will be added, and a forwarding assignment to that property included in the body of the constructor.

 vor PHP 8 war dieses Konstrukt notwendig, um Klasseneigenschaften zuzuweisen:

class Point {
    public float $x;
    public float $y;
    public float $z;
 
    public function __construct(
        float $x = 1.0,
        float $y = 2.0,
        float $z = 3.0,
    ) {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }

Die Eigenschaften werden 1) in der Eigenschaftsdeklaration, 2) den Konstruktorparametern und 3) zweimal in der Eigenschaftszuweisung wiederholt. Darüber hinaus wird der Eigenschaftstyp zweimal wiederholt.

mit Php 8 reicht das:

class Point {
    public function __construct(
        public float $x = 1.0,
        public float $y = 2.0,
        public float $z = 3.0,
    ) {}
}

When a method parameter is prefixed with one of the visibility keywords public, protected or private, it is considered to be “promoted”. For each promoted parameter, a property with the same name will be added, and a forwarding assignment to that property included in the body of the constructor.

 

Analyse

Entwurf

Development

Launch