CKTIS / PHP
Записи и агрегати
Запис се описва с именувани типизирани свойства, промотирани в конструктора.
Версия: PHP 8.4; repository runtime, production runtime not attested
Синтаксис
public function __construct(public readonly int $units) {}Запис се описва с именувани типизирани свойства, промотирани в конструктора. Агрегат проверява правилата на полетата преди завършване. readonly спира повторно присвояване, но не проверява количеството. Отхвърлете отрицателно количество и пазете парите в цели малки единици. Неотрицателни полета не ограничават произведението. Конструкция с PHP_INT_MAX и 2 успява и едва total(): int хвърля TypeError, защото произведението става 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
Примери
<?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);}
Резултат
75 DomainException TypeError