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
- Each
privateparameter becomes a property, no boilerplate assignments. $price = 2.75gives the promoted property a default too.totalreads the properties through$thislike any other method.
Keywords and builtins used here
Orderclassechofunctionnewprivatepublicreturnroundtotal
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.
Step 1 of 3 in Classes, step 16 of 27 in Language basics.