PHP — Classes and constructor properties
PHP constructor property promotion can declare and initialize properties in the constructor’s parameter list. A method can use those properties to calculate a subtotal.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
<?php
$point = (object) ["x" => 2];
echo $point->x, PHP_EOL;
2
Represent an invoice line
Constructor property promotion declares and initializes both private properties. The public subtotal method accesses the object through $this. This syntax requires PHP 8 or later.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
final class LineItem
{
public function __construct(private int $units, private int $cents) {}
public function subtotal(): int
{
return $this->units * $this->cents;
}
}
echo (new LineItem(3, 125))->subtotal(), PHP_EOL;
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.