CKTIS / PHP
Datensätze und Aggregate
Ein Datensatz kann durch benannte typisierte Konstruktor-Eigenschaften beschrieben werden.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __construct(public readonly int $units) {}Ein Datensatz kann durch benannte typisierte Konstruktor-Eigenschaften beschrieben werden. Ein Aggregat prüft Feldregeln vor Abschluss der Konstruktion. readonly verhindert Neuzuweisung und prüft keine Mengen. Negative Mengen abweisen und Geld in ganzzahligen Untereinheiten führen. Nichtnegative Felder begrenzen das Produkt nicht. PHP_INT_MAX und 2 werden beim Bau akzeptiert, erst total(): int wirft TypeError, weil die Multiplikation float ergibt.
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
Beispiele
<?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);}
Ergebnis
75 DomainException TypeError