Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Finite state machines

Represent a closed state set with an enum and express permitted state/event pairs in match arms.

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

Syntax

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

Represent a closed state set with an enum and express permitted state/event pairs in match arms. Each transition returns a new state. A default arm can reject invalid transitions without modifying the current state. Keeping the transition function independent of persistence makes complete transition tests possible.

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

Examples

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

Result

invalid Open

Sources