Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

Macchine a stati finiti

Un enum chiude l’insieme degli stati e i rami match descrivono le coppie stato-evento ammesse.

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

Sintassi

match ([$state, $event]) { /* transitions */ }

Un enum chiude l’insieme degli stati e i rami match descrivono le coppie stato-evento ammesse. La transizione restituisce un nuovo stato. default può respingere un evento prima di modificare lo stato corrente. Una funzione separata dalla persistenza permette di provare ogni transizione.

enum Door{case Closed;case Open;}function step(Door $state,string $event):Door{return match([$state,$event]){[Door::Closed,"open"]=>Door::Open,[Door::Open,"close"]=>Door::Closed,default=>throw new DomainException("invalid")};}
$s=step(Door::Closed,"open");try{$s=step($s,"open");}catch(DomainException $e){echo $e->getMessage()," ";}echo $s->name;
invalid Open

Esempi

<?php
enum Door{case Closed;case Open;}function step(Door $state,string $event):Door{return match([$state,$event]){[Door::Closed,"open"]=>Door::Open,[Door::Open,"close"]=>Door::Closed,default=>throw new DomainException("invalid")};}
$s=step(Door::Closed,"open");try{$s=step($s,"open");}catch(DomainException $e){echo $e->getMessage()," ";}echo $s->name;

Risultato

invalid Open

Fonti