Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Constructor property promotion

Constructor property promotion combines a constructor parameter with a property declaration using a visibility modifier.

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

Syntax

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

Constructor property promotion combines a constructor parameter with a property declaration using a visibility modifier. PHP assigns the incoming value to the property before the constructor body runs. A default belongs to the parameter and applies when the caller omits it. A regular parameter without promotion does not declare a property, and a promoted name cannot be declared again separately.

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]

Examples

<?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")]);

Result

["tea",2,3,false]

Sources