KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / PHP

Records en aggregaten

Beschrijf een record met benoemde getypeerde eigenschappen via constructorpromotie.

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

Syntax

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

Beschrijf een record met benoemde getypeerde eigenschappen via constructorpromotie. Een aggregaat controleert veldregels vóór de constructie klaar is. readonly blokkeert hertoewijzing maar valideert geen aantal. Weiger negatieve aantallen en bewaar geld in gehele kleine munteenheden. Niet-negatieve velden begrenzen het product niet. Constructie met PHP_INT_MAX en 2 lukt, maar total(): int geeft TypeError doordat het product een float wordt.

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

Voorbeelden

<?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);}

Resultaat

75 DomainException
TypeError

Bronnen