typestar

Constructor promotion in PHP

PHP 8 constructors that declare, type and assign properties in one stroke.

<?php
// constructor promotion declares and assigns properties in one place
class Order {
    public function __construct(
        private string $item,
        private int $qty,
        private float $price = 2.75,
    ) {}

    public function total(): float {
        return round($this->qty * $this->price, 2);
    }
}

$order = new Order("flat white", 3);
echo $order->total(), "\n";

How it works

  1. Each private parameter becomes a property, no boilerplate assignments.
  2. $price = 2.75 gives the promoted property a default too.
  3. total reads the properties through $this like any other method.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
340
Tokens
67
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 54 seconds.

Type this snippet

Step 1 of 3 in Classes, step 16 of 27 in Language basics.

← Previous Next →