CKTIS / PHP
Registros y agregados
Describa un registro con propiedades nombradas y tipadas promovidas en el constructor.
Versión: PHP 8.4; repository runtime, production runtime not attested
Sintaxis
public function __construct(public readonly int $units) {}Describa un registro con propiedades nombradas y tipadas promovidas en el constructor. Un agregado comprueba reglas de campos antes de terminar la construcción. readonly impide reasignar pero no valida la cantidad. Rechace cantidades negativas y guarde dinero en unidades menores enteras. Los campos no negativos no limitan el producto. La construcción con PHP_INT_MAX y 2 se acepta, pero total(): int lanza TypeError al convertirse el producto en 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
Ejemplos
<?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);}
Resultado
75 DomainException TypeError