Lesson contents

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

  1. Start with A point with x = 2
  2. Do this Read x
  3. Result 2
A record keeps related values together. Here the program reads a single named field.
lesson.php
<?php
$point = (object) ["x" => 2];
echo $point->x, PHP_EOL;
Output
2
Advertisements

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.

One line item: 3 juices. Price per juice: 125¢. Subtotal: 375¢.
Keep an invoice line together

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
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;
Output
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.

PHP language reference

Related tags

  • PHP
  • data modeling
  • records
  • methods