Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Records and aggregates

Represent a record with named, typed constructor-promoted properties.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

public function __construct(public readonly int $units) {}

Represent a record with named, typed constructor-promoted properties. An aggregate can enforce rules involving several fields before construction succeeds. A readonly field blocks reassignment but does not establish business rules. Reject a negative quantity explicitly and keep monetary amounts in integer minor units. Nonnegative fields do not bound their product: PHP_INT_MAX and 2 pass construction, but total(): int raises TypeError when their multiplication produces a float.

readonly class Line {public function __construct(public int $qty,public int $cents){if($qty<0||$cents<0)throw new DomainException();}public function total():int{return $this->qty*$this->cents;}}
echo (new Line(3,25))->total();try{new Line(-1,25);}catch(DomainException $e){echo " ",get_class($e);}
$big=new Line(PHP_INT_MAX,2);try{$big->total();}catch(TypeError $e){echo "\n",get_class($e);}
75 DomainException
TypeError

Examples

<?php
readonly class Line {public function __construct(public int $qty,public int $cents){if($qty<0||$cents<0)throw new DomainException();}public function total():int{return $this->qty*$this->cents;}}
echo (new Line(3,25))->total();try{new Line(-1,25);}catch(DomainException $e){echo " ",get_class($e);}
$big=new Line(PHP_INT_MAX,2);try{$big->total();}catch(TypeError $e){echo "\n",get_class($e);}

Result

75 DomainException
TypeError

Sources