CKTIS / PHP
Record e aggregati
Descrivere un record con proprietà nominate e tipizzate promosse nel costruttore.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
public function __construct(public readonly int $units) {}Descrivere un record con proprietà nominate e tipizzate promosse nel costruttore. Un aggregato controlla regole sui campi prima della fine della costruzione. readonly impedisce la riassegnazione ma non valida la quantità. Rifiutare quantità negative e tenere gli importi in unità minori intere. I campi non negativi non limitano il prodotto. La costruzione con PHP_INT_MAX e 2 riesce, ma total(): int causa TypeError perché il prodotto diventa 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
Esempi
<?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);}
Risultato
75 DomainException TypeError