A simple class with constructor promotion

Constructor promotion (PHP 8) declares and sets the properties in one place. Type everything.

PHP · A simple class with constructor promotionIntermediate
class Product
{
    public function __construct(
        public string $name,
        private float $price,
        private int $stock = 0,
    ) {}

    public function price(): float
    {
        return $this->price;
    }

    public function inStock(): bool
    {
        return $this->stock > 0;
    }

    public function withDiscount(int $percent): static
    {
        $copy = clone $this;
        $copy->price = round($this->price * (100 - $percent) / 100, 2);
        return $copy;
    }
}

$p = new Product('Mouse', 20.0, 5);
echo $p->withDiscount(25)->price();    // 15
classoopphp8