Enums
An enum is a type with a fixed list of named cases. Each case has a name and a whole number.
Declaring an enum
Declares a new type whose values are a fixed set of named numbers.
Write the cases between { and }, separated by commas. Every case has a whole number behind it. You can write that number with =, or leave it out. The first case with no number written is 0, and every later case with no number written is one more than the case before it. Two cases may have the same number.
enum Level: int and enum Level: uint name the type of number behind the cases. With nothing written it is int.
The body may also declare methods and constants, but no properties. Inside a method, $this is the case the method is called on, as in Level::Info->label().
The examples below show an enum with no numbers written, then an enum whose numbers you choose, then permissions where each case is one bit. In example 04, the cases after a written number get the next numbers. Examples 05 to 07 show three enums that do not compile. Example 08 shows a constant and a method.
The steps of an order
<?nvs// Shows an enum written without any numbers. The first case is 0, and every// case after it is one more than the case before it.
enum Step { Ordered, Packed, Shipped, Delivered }
// `as int` gives the number behind a case. This prints 0, 1, 2 and 3.echo Step::Ordered as int, "\n";echo Step::Packed as int, "\n";echo Step::Shipped as int, "\n";echo Step::Delivered as int, "\n";
// A variable of type `Step` holds one of these four cases and nothing else.Step $current = Step::Packed;
// This prints `packed`.echo $current == Step::Packed ? 'packed' : 'somewhere else', "\n";0123packedThe exit codes of a command
<?nvs// Shows an enum whose cases carry numbers you choose. These are the exit codes// a command line program returns to the shell that started it.
enum Exit: int { Ok = 0, Usage = 64, NoInput = 66, Software = 70, Interrupted = 130 }
// This prints 0, 64 and 130.echo Exit::Ok as int, "\n";echo Exit::Usage as int, "\n";echo Exit::Interrupted as int, "\n";
// You can write a number for the first case only. Every case after it counts on// from the case before it.enum Attempt: int { First = 1, Second, Third }
// This prints 1, 2 and 3.echo Attempt::First as int, "\n";echo Attempt::Second as int, "\n";echo Attempt::Third as int, "\n";064130123What a role may do
<?nvs// Shows why you choose the numbers yourself. Each permission gets a number with// a single bit set, so one `uint` can hold several permissions at once.
class Role{ enum Permission: uint { Read = 1, Write = 2, Delete = 4, Invite = 8 }
// Adds one permission to a set of permissions. public static function add(uint $set, Permission $p): uint { return $set | ($p as uint); }
// Returns `true` when the set contains the permission. public static function has(uint $set, Permission $p): bool { return ($set & ($p as uint)) != 0; }}
uint $editor = Role::add(Role::add(0, Role::Permission::Read), Role::Permission::Write);
// An editor may read and write, and may not delete.// This prints `read: yes`, `write: yes` and `delete: no`.echo Role::has($editor, Role::Permission::Read) ? 'read: yes' : 'read: no', "\n";echo Role::has($editor, Role::Permission::Write) ? 'write: yes' : 'write: no', "\n";echo Role::has($editor, Role::Permission::Delete) ? 'delete: yes' : 'delete: no', "\n";read: yeswrite: yesdelete: noCounting on from a written number
<?nvs// Shows how the numbers of an enum count on after a number you write. A number// may also be negative, and a `uint` enum may use the largest `uint`.
enum Signal: int { Stop = 10, Go, Wait = 30, After }enum Dir { Back = -2, Left, Still, Right }enum Mask: uint { None = 0, All = 18446744073709551615 }
// `Go` is one more than `Stop`, and `After` is one more than `Wait`.// This prints `10,11,30,31`.echo Signal::Stop as int, ',', Signal::Go as int, ',', Signal::Wait as int, ',', Signal::After as int, "\n";
// Counting also works from a negative number. This prints `-2,-1,0,1`.echo Dir::Back as int, ',', Dir::Left as int, ',', Dir::Still as int, ',', Dir::Right as int, "\n";
// A `uint` enum converts with `as uint`. This prints 18446744073709551615.echo Mask::All as uint, "\n";10,11,30,31-2,-1,0,118446744073709551615A case written with case
<?nvs// Shows that a case is not written with `case` and `;`. Write// `enum Suit { Hearts, Spades }`.// proof: compile-error
enum Suit { case Hearts; case Spades; }error[E0239]: an enum case is not written with `case` --> 05-a-case-written-with-case.nvs:6:13 |6 | enum Suit { case Hearts; case Spades; } | ^^^^ remove this keyword = help: an enum body is a list of cases like `Name = 1,`, separated by commas. It has no `case` keyword and no `;`
error[E0239]: an enum case is not written with `case` --> 05-a-case-written-with-case.nvs:6:26 |6 | enum Suit { case Hearts; case Spades; } | ^^^^ remove this keyword = help: an enum body is a list of cases like `Name = 1,`, separated by commas. It has no `case` keyword and no `;`
error: aborting due to 2 errorsTo read what a code means and how to fix it, run `nvs agent show <code>`.A property in an enum
<?nvs// Shows that an enum cannot have a property. A case cannot store a value,// so this does not compile.// proof: compile-error
enum Suit { Hearts, Spades, public int $count = 2;}error[E0220]: an enum has no properties --> 06-a-property-in-an-enum.nvs:9:5 |9 | public int $count = 2; | ^^^^^^^^^^^^^^^^^^^^^^ not a case, a method or a constant = help: an enum case cannot store a value. Keep the value in a class of your own, or return it from a method of the enum
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.An enum of strings
<?nvs// Shows that an enum cannot have text behind its cases. Only `int` and `uint`// are allowed.// proof: compile-error
enum Suit: string { Hearts, Spades }error[E0219]: an enum cannot be backed by `string` --> 07-an-enum-of-strings.nvs:6:12 |6 | enum Suit: string { Hearts, Spades } | ^^^^^^ only `int`/`uint` back an enum = help: use `: int` or `: uint`, or omit the backing type
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.An enum with a constant and a method
<?nvs// Shows an enum with a constant and a method. Inside the method, `$this` is the// case that the method is called on.
enum Priority{ Low, Normal, Urgent,
// The most hours a support ticket may wait for an answer. public const int MAX_WAIT_HOURS = 72;
// Returns the hours a ticket with this priority may wait. public function waitHours(): int { return match ($this) { Priority::Low => self::MAX_WAIT_HOURS, Priority::Normal => 24, Priority::Urgent => 2, }; }}
// This prints 72.echo Priority::MAX_WAIT_HOURS, "\n";
// This prints 2.echo Priority::Urgent->waitHours(), "\n";
// The method also works on a variable. This prints 24.Priority $p = Priority::Normal;echo $p->waitHours(), "\n";72224Details
A case value is a whole number written in the code. It may be negative, and it may be written in hex (0x10), in binary (0b11) or with underscores (1_000). Anything else is the error E0436. That covers a calculation such as 1 << 3, another case, a class constant, a float and a string.
The backing type is the type of number behind the cases, int or uint. A value that does not fit it is the error E0437. enum M: uint { A = -1 } is one example. A case with no value written after a case with the largest possible number is E0437 too. It has no next number.
A comma after the last case is allowed. An enum with no cases compiles.
Two cases with the same value are equal: Suit::A == Suit::B is true when both are 1.
A method or a constant of an enum may be public or private. A method may be static. Inside the enum, self is the enum, so self::Hearts, self::MAX and self::label() work. A method reference such as Suit::Hearts->label(...) gives a function you can call later.
To add a method to an enum from another package or from Core, write an extend block. An extend block for an enum that your own program declares is the error E0337. Write the method in the enum.
The enum name and every case name are PascalCase. A name that starts with a lowercase letter or has an underscore, such as hearts or Big_One, is the error E0110. The help gives the fixed name.
These forms do not compile:
casebefore a case name is the errorE0239.- A property in an enum body is the error
E0220. Its help shows how to keep the value in a class. - An enum inside an enum body is the error
E0220. So is a method that usesyield. - A constant with the same name as a case is the error
E0304. - A
;between cases is a syntax error (E0101). implementson an enum is the errorE0218.enum Suit: stringis the errorE0219. Every other backing type isE0438. Onlyintanduintare allowed.- An enum with the same name as another enum or a class in the file is the error
E0304. - An enum declared inside a method is the error
E0233. Declare it at the top level of the file, or in a class body.
A case that the enum does not have, such as Suit::Clubs, is the error E0309.
When only one class uses an enum, declare the enum inside that class. When several classes use it, declare it at the top level of the file.
An enum inside a class
Declares an enum in the body of the class or interface that uses it.
Write the enum in the body, next to the properties and methods. Inside the body, the enum is Status and a case is Status::Paid. Everywhere else, the enum is Order::Status and a case is Order::Status::Paid. A case is a whole number, the same as in an enum outside a class.
The enum takes no public or private. A subclass does not inherit it, and a class that implements an interface does not inherit the interface's enum. Write Status inside the owner and Order::Status everywhere else. self::Status and use Shop\Order::Status; do not compile. An enum that several classes use is declared outside the classes.
The examples below show an order that keeps its status, a command line program with its own exit codes, and an interface whose enum every class that implements it returns. Then three programs that do not compile: an enum with private, a subclass that names its parent's enum, and a use of an enum.
An order and its status
<?nvs// Shows an order that declares the enum for its own status.
class Order{ enum Status { Open, Paid, Shipped, Cancelled }
// Inside the class, the enum is `Status`. public Status $status = Status::Open;
public function pay(): void { $this->status = Status::Paid; }
public function ship(): void { if ($this->status == Status::Paid) { $this->status = Status::Shipped; } }}
Order $order = new Order();$order->ship();
// The order was not paid, so it is still open. This prints 0.echo $order->status as int, "\n";
$order->pay();$order->ship();
// Outside the class, the enum is `Order::Status`. This prints `shipped`.echo $order->status == Order::Status::Shipped ? 'shipped' : 'not shipped', "\n";0shippedThe exit codes of a command
<?nvs// Shows a command line program that declares its own exit codes as an enum.
final class Import{ enum Exit: int { Ok = 0, Usage = 64, NoInput = 66 }
public static function run(array<string> $files): Exit { if (Core\Arr::count($files) == 0) { return Exit::Usage; } return Exit::Ok; }}
// `as int` gives the number the shell sees. This prints 64 and then 0.echo Import::run([]) as int, "\n";echo Import::run(['orders.csv']) as int, "\n";
// A variable outside the class names the enum with its class.Import::Exit $code = Import::Exit::NoInput;
// This prints 66.echo $code as int, "\n";64066An interface and its enum
<?nvs// Shows an interface that declares an enum, and two classes that return its cases.
interface Job{ enum Result { Done, Retry, Failed }
public function run(): Result;}
// A class that implements `Job` writes the enum as `Job::Result`.final class SendMail implements Job{ public function run(): Job::Result { return Job::Result::Retry; }}
final class CleanUp implements Job{ public function run(): Job::Result { return Job::Result::Done; }}
class Report{ public static function word(Job::Result $r): string { return match ($r) { Job::Result::Done => 'done', Job::Result::Retry => 'retry', Job::Result::Failed => 'failed', }; }}
array<Job> $jobs = [new SendMail(), new CleanUp()];
// This prints `retry` and then `done`.foreach ($jobs as Job $job) { echo Report::word($job->run()), "\n";}retrydoneAn enum with private
<?nvs// Shows that an enum in a class body takes no `private` or `public`. Remove the// word, and the class compiles.// proof: compile-error
class Order { private enum Status { Open, Paid }}error[E0133]: an enum in a class body takes no modifier --> 04-an-enum-with-private.nvs:7:5 |7 | private enum Status { Open, Paid } | ^^^^^^^ remove this = help: the enum's cases can be returned outside the class. A visibility would hide only the enum's name
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A subclass does not inherit the enum
<?nvs// Shows that a subclass does not inherit an enum. `Refund` extends `Order`, but// `Refund::Status` does not exist. Write `Order::Status`.// proof: compile-error
class Order{ enum Status { Open, Paid }}
class Refund extends Order{}
echo Refund::Status::Paid as int, "\n";error[E0309]: `Refund` has no enum named `Status` --> 05-a-subclass-does-not-inherit-the-enum.nvs:15:6 |15 | echo Refund::Status::Paid as int, "\n"; | ^^^^^^^^^^^^^^ referenced here = help: `Order::Status` is where it is declared. An enum in a class body is used through that class. A subclass does not inherit it
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Importing the enum of a class
<?nvs// Shows that `use` cannot import an enum from a class. Write `use Shop\Order;`// and then `Order::Status`.// proof: compile-error
namespace Shop;
use Shop\Order::Status;
class Order { enum Status { Open, Paid }}error[E0212]: an import cannot name a member of a class --> 06-importing-the-enum-of-a-class.nvs:8:15 |8 | use Shop\Order::Status; | ^^^^^^^^ a member of a class = help: import the class with `use Shop\Order;` and write `Order::Status`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
public, private or protected before the enum is the error E0133. The cases leave the class in every value it returns, so a visibility could only hide the name.
A subclass does not inherit the enum. Refund::Status, where Refund extends Order, is the error E0309, and its help names Order::Status. Inside Refund, the name Status alone is the error E0303. The same is true in a class that implements an interface with an enum. Write Order::Status or Job::Result there.
self::Status and static::Status are the error E0135. Inside the class that declares the enum, write Status.
use Shop\Order::Status; is the error E0212. Write use Shop\Order; and then Order::Status.
An enum, a class constant and a type alias in one class must have different names. Two of them with the same name are the error E0304. Two enums with the same name in one class are E0304 too.
An enum body does not declare an enum (E0220). An if block does not declare one either (E0233). A class body declares an enum or a type alias, but not a class or an interface (E0233).
An enum in a class may have the same name as an enum outside the classes. Inside the class, the name means the class's own enum.
Order::Status::class gives the full name of the enum. In the namespace Shop, that is Shop\Order::Status. The enum Status in the class Shop\Order and a class Status in the namespace Shop\Order are two different types. Shop\Order::Status names the enum, and Shop\Order\Status names the class.
Two classes may each declare an enum with the same name. They are two different enums. A::Kind::X == B::Kind::X is the error E0466.
From a case to its number
Turns an enum case into the whole number behind it.
Every case of an enum has a number, and as int gives you that number. This is the only way to get a number from a case. A case has no text form, so echo on a case, a case inside a "..." string, and as string do not compile. To show a case to a person, convert it to its number first, or write your own function that returns a name for each case.
An enum declared as enum E: uint converts with as uint instead, and only with as uint.
Good to know: the number is the value of the case, which is not always its position in the list. The first case is 0, and each later case counts on from the one before it. A case may also set its own value.
The examples below show reading the number, printing a name for a case, and saving a choice as a number. Example 04 shows that as string on a case does not compile.
The number behind a case
<?nvs// Shows the number that belongs to each enum case. `as int` is the only way to// read it.
enum Level { Low, Mid, High }
// The first case is 0, and each later case counts on from the one before it.// This prints 0, 1 and 2.echo Level::Low as int, "\n";echo Level::Mid as int, "\n";echo Level::High as int, "\n";
enum Http { Ok = 200, Created = 201, NotFound = 404 }
// A case can also set its own value. This prints 200, 201 and 404.echo Http::Ok as int, "\n";echo Http::Created as int, "\n";echo Http::NotFound as int, "\n";012200201404Printing a name for a case
<?nvs// Shows how to print an enum case. A case has no text form, so this program// writes a function that returns a name, and prints the number beside it.
class Levels{ enum Level { Low, Mid, High }
// Returns a name a person can read for one case. public static function name(Level $level): string { return match ($level) { Level::Low => 'low', Level::Mid => 'mid', Level::High => 'high', }; }}
array<Levels::Level> $seen = [Levels::Level::High, Levels::Level::Low, Levels::Level::Mid];// This prints `high 2`, then `low 0`, then `mid 1`.foreach ($seen as Levels::Level $level) { echo Levels::name($level), ' ', $level as int, "\n";}high 2low 0mid 1Saving a choice as a number
<?nvs// Shows an order status written to a file as a number. A file, a database// column and a JSON field keep numbers and text, so the case becomes its// number on the way out.
class Order{ enum Status { New, Paid, Shipped, Closed }
public function constructor(public string $reference, public Status $status) {}
// Returns one line of the file: the order reference, then the status as a // number. public function line(): string { return $this->reference . ',' . (($this->status as int) as string); }}
array<Order> $orders = [ new Order('A-1001', Order::Status::Paid), new Order('A-1002', Order::Status::New), new Order('A-1003', Order::Status::Shipped),];
// This prints `A-1001,1`, then `A-1002,0`, then `A-1003,2`.foreach ($orders as Order $order) { echo $order->line(), "\n";}A-1001,1A-1002,0A-1003,2A case as a string
<?nvs// Shows that `as string` on a case does not compile. Write// `(Rank::Silver as int) as string` to get the number as text.// proof: compile-error
enum Rank { Bronze, Silver }echo Rank::Silver as string, "\n";error[E0708]: `Rank` cannot be converted to `string` --> 04-a-case-as-a-string.nvs:7:6 |7 | echo Rank::Silver as string, "\n"; | ^^^^^^^^^^^^^^^^^^^^^^ converted here = help: an enum case is a named integer, not text. Write `$case as int as string`, or write a method that returns its name
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
echo on a case, a case in a "..." string and a case joined with . are the error E0707. A case as the key of an array<T> is the error E0434. Declare the array as array<Level, T> to use the cases as keys.
as float, as decimal and as string on a case are the error E0708. So is as int on a uint enum, and as uint on an int enum. Convert to the backing type first, then to the type you want: (Level::High as int) as string.
as bool on a case compiles, and the result is always true. Every case is true in a condition, also a case whose number is 0.
A case of one enum does not convert to another enum. Mode::Read as Access is the error E0416, also when both enums have a case with the same number. Write a match that names every case.
+, - and the other arithmetic operators on a case are the error E0415. Convert the case with as int first. This also applies to -1 as Level: as runs before the -, so write (-1) as Level.
Core\Json::encode and Core\Debug::dump write a case as its number.
In a mixed variable, a case is stored as an enum case, but its enum is not stored. $value is int is false for it. $value is Level is true when its number belongs to a case of Level, also when it came from another enum.
From a number to a case
Turns a number into the case of an enum that carries it.
$n as Level gives the case whose number is $n. When no case of Level carries that number, it throws a RuntimeError whose message names every case of the enum. Write $n as ?Level where the number comes from outside your program: the result is then null instead of an error, and your program chooses what to do about it.
The value on the left is converted to the enum's backing type first, so text and a float reach a case too. "10" as Level converts the text to 10 and then looks for the case. Text that is not a number gives null under as ?Level, and throws under as Level.
The examples below convert a number that names a case, then show what happens when no case carries the number, then read a setting that arrives as text.
A number that names a case
<?nvs// Shows how a number becomes a case of an enum. `as Level` looks for the case// that carries the number.
enum Level: int { Debug = 0, Info = 1, Warn = 2, Error = 3 }
int $stored = 2;Level $level = $stored as Level;
// This prints `warn`.echo $level == Level::Warn ? 'warn' : 'something else', "\n";
// The number comes back out with `as int`. This prints 2.echo $level as int, "\n";
// Text is converted to the number first, so this also finds `Level::Error`.Level $fromText = '3' as Level;
// This prints 3.echo $fromText as int, "\n";warn23A number that names no case
<?nvs// Shows the two ways to convert a number that no case carries. `as Level`// throws an error. `as ?Level` returns `null`.
enum Level: int { Debug = 0, Info = 1, Warn = 2, Error = 3 }
// The message names every case of the enum, so you can see what was expected.try { Level $level = 9 as Level; echo "this line is never reached\n";} catch (RuntimeError $e) { echo $e->message, "\n";}
// `as ?Level` gives `null` for the same number, and throws nothing.?Level $maybe = 9 as ?Level;
// This prints `no such level`.echo $maybe == null ? 'no such level' : 'found one', "\n";
// Text that is not a number gives `null` as well.?Level $fromText = 'loud' as ?Level;
// This prints `no such level`.echo $fromText == null ? 'no such level' : 'found one', "\n";`9` is not one of `Level::Debug`, `Level::Info`, `Level::Warn`, `Level::Error`no such levelno such levelA setting that arrives as text
<?nvs// Shows how a program reads a setting written by somebody else. The text may// name no case, so the program uses `as ?Level` and keeps its own default.
class Settings{ enum Level: int { Debug = 0, Info = 1, Warn = 2, Error = 3 }
// Returns the level the text names. Returns `Level::Info` when the text // names no level. public static function level(string $text): Level { ?Level $found = $text as ?Level; if ($found == null) { return Level::Info; } return $found; }
// Returns `true` when a message at this level should be written. public static function writes(Level $configured, Level $message): bool { return ($message as int) >= ($configured as int); }}
array<string> $lines = ['2', '0', 'verbose', ''];
// The first two lines name a level. The last two do not, so both become// `Settings::Level::Info`. This prints 2, 0, 1 and 1.foreach ($lines as string $line) { echo Settings::level($line) as int, "\n";}
Settings::Level $configured = Settings::level('2');
// A warning is written and a debug message is not. This prints `yes` and `no`.echo Settings::writes($configured, Settings::Level::Warn) ? 'yes' : 'no', "\n";echo Settings::writes($configured, Settings::Level::Debug) ? 'yes' : 'no', "\n";2011yesnoDetails
The value is first converted to the backing type, with the rules of as int or as uint. Then the enum is searched for a case with that number. Each step can fail:
- A number that no case has throws a
RuntimeError. The message lists every case of the enum. - Text that is not a whole number throws a
RuntimeError. Text with a space, such as" 1", and text with a fraction, such as"2.0", are not whole numbers. - A
floatwith a fraction, such as1.5, throws anArithmeticError. Afloatwithout one, such as2.0, finds the case with the number2. - A negative number for a
uintenum throws anArithmeticError. nullthrows aRuntimeError.
as ?Level gives null in each of these cases, and throws nothing.
ArithmeticError is not a kind of RuntimeError. A catch (RuntimeError $e) does not catch it.
When two cases have the same number, the result is equal to both of them.
A mixed value and a tainted string convert the same way. as Level does not convert a bool: true as Level is the error E0708.
An enum has no from or tryFrom method. Level::from(1) is the error E0309. Write 1 as Level or 1 as ?Level.
Comparing cases
Compares two cases of one enum.
== is true when both sides are the same case, and != is true when they are different. Both sides must belong to the same enum. A case compared against a plain number, or against a case of another enum, does not compile: the two types have no value in common, so the comparison could only ever be false.
There is no < or > between cases. Write $case as int on both sides and compare the numbers, which is also how you subtract or add them. That keeps the order you get explicit, because the order of the cases is the order of the numbers you gave them.
The examples below show == and != between cases, then the number comparison that puts two cases in order, then a page that decides what a visitor may do from a role. Example 04 shows that a case compared with a number does not compile.
Testing which case a value is
<?nvs// Shows how to compare two cases of one enum. `==` is true when both sides are// the same case. `!=` is true when they are different cases.
enum Rank { Bronze, Silver, Gold }
Rank $held = Rank::Silver;
// This prints `the same`.if ($held == Rank::Silver) { echo "the same\n";}
// This prints `not gold`.if ($held != Rank::Gold) { echo "not gold\n";}
Rank $other = Rank::Gold;
// This prints `different`. Two variables compare the same way as a variable and// a case.if ($held != $other) { echo "different\n";}the samenot golddifferentPutting two cases in order
<?nvs// Shows how to test whether one case is higher than another. `<` and `>` do not// work on cases. Convert both sides with `as int` and compare the numbers.
enum Rank { Bronze = 1, Silver = 2, Gold = 3 }
Rank $held = Rank::Silver;
// This prints `below gold`. `Silver` is 2 and `Gold` is 3.if (($held as int) < (Rank::Gold as int)) { echo "below gold\n";}
// This prints `at least bronze`. `Bronze` is 1.if (($held as int) >= (Rank::Bronze as int)) { echo "at least bronze\n";}
// The numbers work in arithmetic as well. This prints 1.echo (Rank::Gold as int) - ($held as int), "\n";below goldat least bronze1What a visitor may do on a page
<?nvs// Shows a page that decides what a visitor may do. The role arrives as an enum.// `==` tests for one role, and `as int` compares two roles by their number.
class Page{ enum Role { Guest = 0, Member = 10, Editor = 20, Owner = 30 }
public static function actions(Role $role): string { // A guest is a single case, so `==` is the test for it. if ($role == Role::Guest) { return 'read'; } // Everybody from `Editor` upwards may publish, so the numbers decide. if (($role as int) >= (Role::Editor as int)) { return 'read, comment, publish'; } return 'read, comment'; }}
array<Page::Role> $visitors = [Page::Role::Guest, Page::Role::Member, Page::Role::Owner];
// This prints `read`, then `read, comment`, then `read, comment, publish`.foreach ($visitors as Page::Role $role) { echo Page::actions($role), "\n";}readread, commentread, comment, publishA case and a number
<?nvs// Shows that a case cannot be compared with a number. Write// `(Rank::Bronze as int) == 0` to compare the numbers.// proof: compile-error
enum Rank { Bronze, Silver }echo (Rank::Bronze == 0) ? 'bronze' : 'other', "\n";error[E0466]: `Rank` and `int` are disjoint; no value is both, so this comparison is always false --> 04-a-case-and-a-number.nvs:7:7 |7 | echo (Rank::Bronze == 0) ? 'bronze' : 'other', "\n"; | ^^^^^^^^^^^^^^^^^ compared here = help: an enum case carries an integer — compare `$e as int` against the number
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A case compared with == or != to a number, a string or a case of another enum is the error E0466. A case compared to null is E0466 too, unless the variable has a type such as ?Level that allows null. A ?Level variable that contains a case compares with that case as usual.
<, >, <=, >= and <=> on two cases are the error E0715. Convert both sides with as int.
== compares numbers. When both sides have the type Level, only cases of Level are compared. In a mixed variable, a case does not keep which enum it belongs to. There, == is true between a case and a plain number with the same value, and between cases of two enums with the same number. Core\Arr::contains compares the same way.
match and switch over an enum
Chooses what to do for each case of an enum.
match and switch both compare the subject with each case label, from the first one written to the last. match is an expression: it returns the value of the arm that fits, and nothing runs after that arm. A match over an enum must handle every case. Write an arm for each case, or a default arm for the cases you do not name. If a case is missing, the program does not compile.
switch runs statements instead of returning a value. An arm ends at its break. An arm without a break runs on into the arm written below it, which is useful when one case needs everything a later case does and a little more.
The examples below show a match with a default arm, then the error a match over a mixed value throws when no arm fits, then a switch whose first arm runs on into the second, and last a match that misses a case.
Choosing a text for each case
<?nvs// Shows a `match` that gives one text for each case of an enum. `match` tries// the arms from top to bottom and returns the first one that fits.
class Name{ enum Mode { Read, Write, Exec }
public static function of(Mode $mode): string { return match ($mode) { Mode::Read => 'read', Mode::Write => 'write', // `default` is used for every case that no arm above names. default => 'other', }; }}
// This prints `write`.echo Name::of(Name::Mode::Write), "\n";
// This prints `other`. No arm names `Exec`, so the `default` arm is used.echo Name::of(Name::Mode::Exec), "\n";writeotherA match without a default throws
<?nvs// Shows what happens when no arm fits and there is no `default`. The `match`// throws an error, which you can catch. This can only happen with a `mixed`// value: a `match` over an enum type must handle every case.
enum Mode { Read, Write, Exec }
// The type of `$value` is `mixed`, so the `match` needs no arm for `Mode::Exec`.mixed $value = Mode::Exec;
try { string $name = match ($value) { Mode::Read => 'read', Mode::Write => 'write', }; echo $name, "\n";} catch (Throwable $error) { // This prints the message: no `match` arm matched the subject. echo $error->message, "\n";}
// A `match` with a `default` arm returns a value for every case. This// prints `other`.Mode $mode = Mode::Exec;echo match ($mode) { Mode::Read => 'read', default => 'other' }, "\n";no `match` arm matched the subjectotherThe next step for each order
<?nvs// Shows the next step to take for each order in a list. A `switch` runs// statements instead of returning a value, and `break` ends an arm. An arm// without `break` runs on into the arm below it.
class Work{ enum Stage { Placed, Paid, Shipped }
public static function next(Stage $stage): string { string $todo = ''; switch ($stage) { case Stage::Placed: $todo = $todo . 'take the payment; '; // No `break` here, so a new order is also packed. case Stage::Paid: $todo = $todo . 'pack the box'; break; case Stage::Shipped: $todo = $todo . 'send the tracking number'; break; } return $todo; }}
array<Work::Stage> $orders = [Work::Stage::Placed, Work::Stage::Paid, Work::Stage::Shipped];
// This prints `take the payment; pack the box`, then `pack the box`, then// `send the tracking number`.foreach ($orders as Work::Stage $stage) { echo Work::next($stage), "\n";}take the payment; pack the boxpack the boxsend the tracking numberA match that misses a case
<?nvs// Shows a `match` over an enum with no arm for `Mode::Exec` and no `default`.// This program does not compile. Add an arm for `Mode::Exec` or a `default` arm.// proof: compile-error
enum Mode { Read, Write, Exec }
Mode $mode = Mode::Write;echo match ($mode) { Mode::Read => 'read', Mode::Write => 'write',}, "\n";error[E1016]: this `match` does not handle `Mode::Exec` --> 04-a-match-that-misses-a-case.nvs:9:6 |9 | echo match ($mode) { | ^^^^^ a case of the enum has no arm here = help: Add an arm for each missing case, or add a `default` arm. = suggestion (review): add the missing arm
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A match over an enum must handle every case. When the subject has an enum type such as Mode, and the match has no default arm, each case needs an arm. A missing case does not compile (E1016), and the message names each missing case. For a subject of type ?Mode, an arm must also handle null. In the editor, the quick fix for E1016 adds one arm for each missing case.
An arm covers a case when its label is that case, or a class constant whose value is that case. Any other label covers no case, so that match needs a default arm.
A match over a mixed value is not checked, because the compiler does not know which enum the value belongs to. When no arm fits and there is no default, it throws a LogicError when the program runs.
A label must be a case of the subject's enum. A case of another enum is the error E0466, and so is a number such as 1. This is the same in a match arm and in a switch case. A null label is E0466 too, unless the subject has a type such as ?Mode that allows null.
An arm for Mode::Read does not narrow the subject. Inside that arm, $m still has the type Mode. Passing it to a parameter of the type Mode::Read is the error E0401. The same is true inside a switch case. Write match (true) with the arm $m == Mode::Read to narrow $m in that arm.
A switch does not need a case for every case of the enum. A switch with no matching case and no default runs none of its code. It does not throw.
When the subject has a smaller type such as Mode::Read|Mode::Write, an arm for Mode::Exec still compiles. That arm never runs.
The labels are still cases when the subject is mixed. The match compares each label by its number. A mixed variable that contains the number 1 matches the arm Mode::Write when Write is the case with the number 1.
An enum as a type
Uses an enum's name as a type.
An enum is a type like int or string, and you can write its name anywhere a type is written: a property, a parameter, a return type, the element type of an array<Suit>, the variable of a foreach loop, and the type a generator gives with Iterator<Suit>. Everything declared that way accepts the cases of that enum and no other value. A number or a string there does not compile.
An array of type array<Suit, T> uses the cases of Suit as its keys. The next section, An enum as an array key, shows how.
The examples below show the type on a property, a parameter and a return value, then an array of cases and two loops over one, then a list of orders that reads a text label from a table.
A type for a property and a method
<?nvs// Shows an enum used as a type. The name `Level` is the type of a property, of// a parameter and of a return value. Each of them accepts the three cases of// `Level` and no other value.
class Gate{ enum Level { Low = 1, Mid = 5, High = 9 }
// This property stores one case of `Level`. public Level $level;
public function constructor(Level $level) { $this->level = $level; }
// The parameter and the return type are both `Level`. public function raise(Level $to): Level { if (($to as int) > ($this->level as int)) { $this->level = $to; } return $this->level; }}
var $gate = new Gate(Gate::Level::Low);
// This prints 5. `Mid` is higher than `Low`, so the gate moves up to `Mid`.echo $gate->raise(Gate::Level::Mid) as int, "\n";
// This prints 5 again. `Low` is lower, so the gate stays at `Mid`.echo $gate->raise(Gate::Level::Low) as int, "\n";55A type for an array and a loop
<?nvs// Shows an enum as the element type of an array and as the type of a loop// variable. `array<Deck::Suit>` is an array where every element is one case of// `Deck::Suit`.
class Deck{ enum Suit { Clubs, Hearts, Spades }
// A generator declared `Iterator<Suit>` gives one case at a time. public static function red(): Iterator<Suit> { yield Suit::Hearts; }}
array<Deck::Suit> $hand = [Deck::Suit::Spades, Deck::Suit::Clubs];
// This prints 2 and then 0. The loop variable is declared `Deck::Suit`.foreach ($hand as Deck::Suit $card) { echo $card as int, "\n";}
// This prints 1. The generator gives cases of `Deck::Suit`, so the loop// variable is a `Deck::Suit` here too.foreach (Deck::red() as Deck::Suit $card) { echo $card as int, "\n";}201A status column for a list of orders
<?nvs// Shows a list of orders printed with a text label for each status. A case is// not an array key, so the table of labels is indexed with `$status as int`.
class Order{ enum Status { Placed, Paid, Shipped }
public function constructor(public string $reference, public Status $status) {}}
class Labels{ // The keys are the numbers behind the cases: 0, 1 and 2. public static function table(): array<string> { array<string> $labels = []; $labels[Order::Status::Placed as int] = 'waiting for payment'; $labels[Order::Status::Paid as int] = 'ready to ship'; $labels[Order::Status::Shipped as int] = 'on its way'; return $labels; }}
array<Order> $orders = [ new Order('A-1042', Order::Status::Shipped), new Order('A-1043', Order::Status::Placed),];
var $labels = Labels::table();
// This prints `A-1042: on its way` and then `A-1043: waiting for payment`.foreach ($orders as Order $order) { echo $order->reference, ': ', $labels[$order->status as int], "\n";}A-1042: on its wayA-1043: waiting for paymentDetails
A variable of the type Suit accepts only the cases of Suit. A number, a case of another enum and an array<Suit> element of another type are the error E0401. A foreach variable declared with another enum is E0401 too. A method that declares Suit and returns a number is the error E0403.
var $s = Suit::Hearts; gives $s the type Suit. Assigning 1 to it later is E0401.
A property of an enum type has no default value. Give it one, such as public Suit $suit = Suit::Hearts;, or assign it in the constructor. Without either, the class does not compile (E0409). A parameter may have a case as its default value: Suit $suit = Suit::Hearts.
?Suit accepts a case or null.
Core\Json::encode writes an array<Suit> as an array of numbers: [0,1].
An enum as an array key
Uses the cases of an enum as the keys of an array.
You write the type as array<Status, int>. The first type argument is the enum, and the second is the type of the values. Every key of the array is a case of Status. A key that is a number, a string or a case of another enum does not compile. To use a number as a key, convert it first with as Status.
When you loop over the array with foreach, the key has the type Status. So you can pass it to a match or to a method that needs a Status. A class constant can be such an array. Use one for a label or a limit for each case.
Good to know: you cannot add a value with $array[] = $value, because there is no next key. Write the case as the key: $array[Status::Paid] = $value.
The examples below show a constant table that gives a label for each case, then a count of orders for each status, then a JSON object read into an array keyed by an enum and filtered.
A label for each case
<?nvs// Shows a constant table that gives a text label for each case of an enum.
enum Priority { Low, Normal, Urgent }
class Ticket{ // The keys of this table are cases of `Priority`. public const array<Priority, string> LABELS = [ Priority::Low => 'can wait', Priority::Normal => 'this week', Priority::Urgent => 'today', ];}
array<Priority> $queue = [Priority::Urgent, Priority::Low, Priority::Normal];
// The case is the key. You do not need to write `as int`. This prints `today`, then// `can wait`, then `this week`.foreach ($queue as Priority $priority) { echo Ticket::LABELS[$priority], "\n";}todaycan waitthis weekCounting orders by status
<?nvs// Shows how to count the orders in each status with an array keyed by an enum.
enum Status { Placed, Paid, Shipped }
array<Status> $orders = [Status::Paid, Status::Placed, Status::Paid, Status::Shipped, Status::Paid];
// Every count starts at 0, so each status has a key.array<Status, int> $counts = [Status::Placed => 0, Status::Paid => 0, Status::Shipped => 0];foreach ($orders as Status $status) { $counts[$status] = $counts[$status] + 1;}
// The key of this loop is a case of `Status`, so a `match` can name each case.foreach ($counts as Status $status => int $count) { string $name = match ($status) { Status::Placed => 'placed', Status::Paid => 'paid', Status::Shipped => 'shipped', }; echo $name, ': ', $count, "\n";}placed: 1paid: 3shipped: 1Settings read from json
<?nvs// Shows how to read a JSON object into an array keyed by an enum, and then filter it.
enum Channel { Email = 1, Sms = 2, Push = 3 }
class Notify{ public static function name(Channel $channel): string { return match ($channel) { Channel::Email => 'email', Channel::Sms => 'sms', Channel::Push => 'push', }; }}
// Each key in this JSON text is the number of a case of `Channel`.string $json = '{"1": true, "2": false, "3": true}';
// `as` checks that every key is a case of `Channel`. If one is not, it throws an error.array<Channel, bool> $enabled = Core\Json::decode($json) as array<Channel, bool>;
// `Core\Arr::filter` keeps the keys, so the result also has `Channel` keys.array<Channel, bool> $on = Core\Arr::filter($enabled, fn(bool $value) => $value);
// `Core\Arr::keys` returns the cases. This prints `email`, then `push`.foreach (Core\Arr::keys($on) as Channel $channel) { echo 'send by ', Notify::name($channel), "\n";}
// With `as ?array<Channel, bool>`, a key that is not a case gives `null`. This prints `7 is not a channel`.?array<Channel, bool> $wrong = Core\Json::decode('{"7": true}') as ?array<Channel, bool>;echo $wrong == null ? '7 is not a channel' : 'accepted', "\n";send by emailsend by push7 is not a channelDetails
The first type argument of array<K, T> is optional. When you write it, it must be an enum. A key type such as string or int is the error E1017. The type array<T> with one argument keeps its usual keys.
A key of an array<Status, T> must be a case of Status. The compiler checks the key when you write a value, when you read a value and in an array literal. A key of type int, string or mixed is the error E0434. A case of another enum is E0434 too. The help for E0434 shows how to convert the key with as Status.
$array[] = $value is the error E1018. An array keyed by an enum has no next key to add a value under.
In a foreach over an array<Status, T>, the key has the type Status. A callback that Core\Arr::filter or Core\Arr::map calls with a key also gets a Status.
Core\Arr::keys returns an array<Status>. Core\Arr::firstKey, Core\Arr::lastKey, Core\Arr::keyOf and Core\Arr::findKey return a Status, or null when there is no such key. Core\Arr::filter, Core\Arr::map and the other functions that keep the keys return an array that is also keyed by Status. Core\Arr::groupBy with a callback that returns a Status returns an array keyed by Status.
You can pass an array<Status, T> to a parameter of type array<T>. To pass an array<T> where an array<Status, T> is needed, convert it with as array<Status, T>.
$value as array<Status, T> checks every key and every value. A key that is not the number of a case of Status throws a RuntimeError. With as ?array<Status, T>, the result is null instead. Use this conversion for an array from Core\Json::decode. Its keys are strings such as "2", and each one must be the number of a case.
Core\Json::encode writes each key as the number of its case, as a JSON string such as "2".
An array keyed by an enum is stored like any other array. It uses the same memory as an array<T> with the same values.
Only some cases
Writes a type that accepts only some of an enum's cases.
Where a type is written you can name two or more cases of one enum with | between them, as in Mode::Read|Mode::Write. A variable, a parameter, a property or a return type declared that way accepts those cases and nothing else. A value typed as the whole enum does not fit, even when it is one of the named cases while the program runs.
Such a value enters the smaller type with as Mode::Read|Mode::Write, which throws an error when the value is not one of the named cases. as ?Mode::Read|Mode::Write returns null instead of throwing.
Good to know: the smaller type fits everywhere the whole enum is wanted, so you never need a conversion in that direction.
The examples below show the type on a parameter, the two conversions into it, a web handler that takes only the two requests it is written for, and a case outside the type that does not compile.
A type that accepts only some cases
<?nvs// Shows a parameter that accepts two of an enum's four cases. Writing the cases// with `|` between them makes a type of its own.
// `Mode` stays outside the classes, because `File` and `Log` both use it.enum Mode { Read, Write, Append, Exec }
class File{ // This parameter accepts `Mode::Read` and `Mode::Write`. No other case of // `Mode` compiles here. public static function open(Mode::Read|Mode::Write $mode): string { return 'opened in mode ' . (($mode as int) as string); }}
// This prints `opened in mode 0` and `opened in mode 1`.echo File::open(Mode::Read), "\n";echo File::open(Mode::Write), "\n";
// A value of the smaller type fits everywhere the whole enum is wanted.class Log{ public static function line(Mode $mode): string { return 'mode=' . (($mode as int) as string); }}
Mode::Read|Mode::Write $chosen = Mode::Write;// This prints `mode=1`.echo Log::line($chosen), "\n";opened in mode 0opened in mode 1mode=1Letting a value into the smaller type
<?nvs// Shows the two ways a value of the whole enum enters a smaller type. One// throws an error when the value is not one of the named cases, the other// returns `null`.
class File{ enum Mode { Read, Write, Append, Exec }
public static function open(Mode::Read|Mode::Write $mode): string { return 'opened in mode ' . (($mode as int) as string); }}
File::Mode $wanted = File::Mode::Write;// `as File::Mode::Read|File::Mode::Write` checks the value while the program// runs. This prints `opened in mode 1`.echo File::open($wanted as File::Mode::Read|File::Mode::Write), "\n";
File::Mode $other = File::Mode::Exec;try { echo File::open($other as File::Mode::Read|File::Mode::Write), "\n";} catch (RuntimeError $error) { // The message names every case the type accepts. echo 'stopped: ', $error->message, "\n";}
// `as ?File::Mode::Read|File::Mode::Write` returns `null` for a value outside// the set. This prints `no mode`.var $maybe = $other as ?File::Mode::Read|File::Mode::Write;if ($maybe == null) { echo "no mode\n";} else { echo File::open($maybe), "\n";}opened in mode 1stopped: `3` is not one of `File::Mode::Read`, `File::Mode::Write`no modeA cache that serves only read requests
<?nvs// Shows a cache that serves only two kinds of web request. The method of the// request arrives as the whole enum, and `as ?` decides whether this cache can// handle it.
// `Method` stays outside the classes, because `Cache` and `Router` both use it.enum Method { Get, Head, Post, Put, Delete }
class Cache{ // Only a request that reads can be served from a cache, so this parameter // accepts those two cases and nothing else. public static function serve(Method::Get|Method::Head $method): string { if ($method == Method::Head) { return 'sent the headers'; } return 'sent the page'; }}
class Router{ public static function handle(Method $method): string { var $readOnly = $method as ?Method::Get|Method::Head; if ($readOnly == null) { return 'passed to the application'; } return Cache::serve($readOnly); }}
array<Method> $incoming = [Method::Get, Method::Head, Method::Post];// This prints `sent the page`, then `sent the headers`, then// `passed to the application`.foreach ($incoming as Method $method) { echo Router::handle($method), "\n";}sent the pagesent the headerspassed to the applicationA case outside the type
<?nvs// Shows that a case outside the smaller type does not compile. `Mode::Exec` is// not one of the two cases that `Open::file` accepts.// proof: compile-error
enum Mode { Read, Write, Exec }
class Open{ public static function file(Mode::Read|Mode::Write $mode): int { return $mode as int; }}
echo Open::file(Mode::Exec), "\n";error[E0401]: expected `Mode::Read|Mode::Write`, found `Mode` --> 04-a-case-outside-the-type.nvs:16:17 |16 | echo Open::file(Mode::Exec), "\n"; | ^^^^^^^^^^ this is `Mode`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
When the parameter is Mode::Read|Mode::Write, Open::file(Mode::Exec) and Open::file($m) with a Mode variable give the same error: E0401, `expected Mode::Read|Mode::Write, found Mode . A method that declares the smaller type and returns another case is the error E0403. An array literal of the type array<Mode::Read|Mode::Write> with another case in it is E0401`.
A type may name one case alone, such as Mode::Read. It may also name cases of two enums, or name the same case twice.
if ($m == Mode::Read) narrows $m to the type Mode::Read inside the block. This works on a variable of the whole enum and on a variable of a smaller type. Nothing else narrows to a smaller type:
$m == Mode::Read || $m == Mode::Writedoes not narrow$mtoMode::Read|Mode::Write.- The
elseblock of$m == Mode::Read, and the block of$m != Mode::Read, keep the whole type. - An arm of
match ($m)keeps the whole type.
Write $m as Mode::Read|Mode::Write for a set of two or more cases.
$m is Mode::Read|Mode::Write is true when $m is one of the two cases.
as also converts a number. 1 as Mode::Read|Mode::Write gives Mode::Write. A number written in the code that is not one of the cases is the error E0470. A number in a mixed variable is checked while the program runs. When it is not one of the cases, the RuntimeError message names the cases the type accepts.
?Mode::Read|Mode::Write and Mode::Read|Mode::Write|null both accept null as well.
A type alias may name a set of cases: type Rw = Mode::Read|Mode::Write;.
$m == Mode::Exec compiles when $m has the type Mode::Read|Mode::Write. The result is always false.
Names and lists of cases
Says what an enum does not have, and what to write instead.
A case is a number with a name, not an object. It has no ->name and no ->value, and an enum has no cases(), from() or tryFrom(). An enum has no properties and cannot implement an interface.
You write these things yourself. $case as int gives the number of a case. $n as Level and $n as ?Level turn a number back into a case. For the name of a case, give the enum a method with a match on $this. For a list of every case, give it a static method that returns array<Level>. The compiler does not check that the match names every case. A case with no arm throws a LogicError when it reaches the match.
The examples below show the name of a case, then the list of every case with a lookup by name, then an enum that carries the behaviour of an order. Examples 04 and 05 show that ->name and cases() do not compile.
The name of a case
<?nvs// Shows how to get the name of a case. A case has no `->name`, so the enum// gets a method with a `match` that returns the name.
enum Level{ Debug, Info, Warn,
// Returns the name of this level. The `match` has an arm for every case. // Add an arm here when you add a case to the enum. public function name(): string { return match ($this) { Level::Debug => 'debug', Level::Info => 'info', Level::Warn => 'warn', }; }}
// This prints `info` and `warn`.echo Level::Info->name(), "\n";echo Level::Warn->name(), "\n";
// The number behind a case needs no method. This prints 2.echo Level::Warn as int, "\n";infowarn2A list of every case
<?nvs// Shows the list of every case. An enum has no `cases()`, so the list is a// static method of the enum that returns `array<Level>`.
enum Level{ Debug, Info, Warn,
public static function all(): array<Level> { return [Level::Debug, Level::Info, Level::Warn]; }
public function name(): string { return match ($this) { Level::Debug => 'debug', Level::Info => 'info', Level::Warn => 'warn', }; }
// Returns the level with this name, or `null` when there is none. public static function byName(string $wanted): ?Level { foreach (self::all() as Level $l) { if ($l->name() == $wanted) { return $l; } } return null; }}
// This prints `debug`, `info` and `warn`, one per line.foreach (Level::all() as Level $l) { echo $l->name(), "\n";}
// This prints 3.echo Core\Arr::count(Level::all()), "\n";
// A name nobody wrote gives `null`, so the program picks its own level.// This prints 1.echo (Level::byName('loud') ?? Level::Info) as int, "\n";debuginfowarn31An enum that carries the behaviour
<?nvs// Shows methods in an enum. The enum has the states of an// order, and its methods say what each state means.
enum Status{ Placed, Paid, Shipped, Cancelled,
// Returns the text shown to a customer for this status. public function label(): string { return match ($this) { Status::Placed => 'waiting for payment', Status::Paid => 'ready to ship', Status::Shipped => 'on its way', Status::Cancelled => 'cancelled', }; }
// Returns `true` when nothing more happens to an order in this status. public function isFinal(): bool { return $this == Status::Shipped || $this == Status::Cancelled; }
// Returns the status after this one, or `null` when there is none. public function next(): ?Status { return match ($this) { Status::Placed => Status::Paid, Status::Paid => Status::Shipped, Status::Shipped => null, Status::Cancelled => null, }; }}
Status $order = Status::Paid;
// This prints `ready to ship` and `no`.echo $order->label(), "\n";echo $order->isFinal() ? 'yes' : 'no', "\n";
// The order moves to its next status. This prints `on its way` and `yes`.?Status $after = $order->next();if ($after != null) { echo $after->label(), "\n"; echo $after->isFinal() ? 'yes' : 'no', "\n";}ready to shipnoon its wayyesA case has no name
<?nvs// Shows that a case has no `->name`. This line does not compile. Give the// enum a method with a `match` instead, as example 01 does.// proof: compile-error
enum Level { Debug, Info }
echo Level::Info->name, "\n";error[E0405]: `Level` has no property named `name` --> 04-a-case-has-no-name.nvs:8:6 |8 | echo Level::Info->name, "\n"; | ^^^^^^^^^^^ referenced here
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.An enum has no cases method
<?nvs// Shows that an enum has no `cases()` method. This line does not compile.// Give the enum a static method that returns `array<Level>`, as example 02 does.// proof: compile-error
enum Level { Debug, Info }
Level::cases();error[E0309]: `Level` has no method named `cases` --> 05-an-enum-has-no-cases-method.nvs:8:1 |8 | Level::cases(); | ^^^^^ referenced here
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
These forms do not compile:
->name,->valueor any other property on a case is the errorE0405. A write such as$level->value = 1isE0405too.- A call of a method that the enum does not declare, such as
Level::Info->label(), is the errorE0405. Level::from($n),Level::tryFrom($n)andLevel::cases()are the errorE0309. So is a constant that the enum does not declare, such asLevel::COUNT, and a static property such asLevel::$x.- A property in an enum body is the error
E0220. implementson an enum is the errorE0218.extendsafter an enum name is a syntax error (E0101).abstractorfinalbeforeenumis a syntax error (E0101).cloneon a case is the errorE0781.
A case is not an object. Putting a case in an object variable is the error E0401, and $case is object is false.
Level::class gives the full name of the enum. Level::Info::class is the error E0702.
Many Core methods take an enum from Core, such as Core\Arr::Order, Core\RoundMode or
Core\Time\Weekday. They work like your own enums. Reference lists every one. To add a method to a
Core enum, write an extend block.
Enums from Core
The enums that come with Novis. They work exactly like the ones you write yourself.
Core\Arr::Order chooses the direction of a sort. It is declared in the class Core\Arr, whose methods use it. Core\RoundMode chooses how a number is rounded. The Core reference lists the rest.
A case is written Core\Arr::Order::Desc. You pass it to a method that needs it. You can keep it in a variable of type Core\Arr::Order and compare it with ==. You can use it in a match and convert it to its number with as int.
Like your own enums, they have no ->value. To add a method to one, write an extend block: a block that adds members to a type from Core.
as Core\Arr::Order or as ?Core\Arr::Order converts a number back into a case. A method that takes one of these enums accepts only its cases. A wrong value is an error when the program is compiled.
The examples below sort with Core\Arr::Order, round a bill with Core\RoundMode, then turn the text a visitor sent into a sort order. Example 04 shows that a number in place of a case does not compile.
Sorting the largest first
<?nvs// Shows the enum that chooses the direction of a sort. `Core\Arr::Order` is an// ordinary enum. You pass one of its cases to a method that needs it.
array<int> $scores = [3, 1, 2];
// This prints 3, 2 and 1, the largest first.foreach (Core\Arr::sort($scores, { order: Core\Arr::Order::Desc }) as int $s) { echo $s, "\n";}
// Leaving the option out sorts the other way. This prints 1, 2 and 3.foreach (Core\Arr::sort($scores) as int $s) { echo $s, "\n";}
// The number behind a case comes out with `as int`, as it does for an enum of// your own. This prints 0 and 1.echo Core\Arr::Order::Asc as int, "\n";echo Core\Arr::Order::Desc as int, "\n";32112301Rounding a shared bill
<?nvs// Shows a `Core` enum that chooses how a number is rounded. You write one of// its cases where the member asks for it.
decimal $bill = 100.00;decimal $people = 3;
// The share of a bill between three people, to two decimal places. `HalfUp`// gives 33.33 and `Up` gives 33.34.echo Core\Decimal::divideRounded($bill, $people, 2, Core\RoundMode::HalfUp), "\n";echo Core\Decimal::divideRounded($bill, $people, 2, Core\RoundMode::Up), "\n";
// A case is a value like any other, so you can keep it in a variable and pass// it later. This prints 33.3333.Core\RoundMode $mode = Core\RoundMode::HalfUp;echo Core\Decimal::divideRounded($bill, $people, 4, $mode), "\n";33.3333.3433.3333A direction that arrives as text
<?nvs// Shows a `Core` enum used the way your own enums are used. A class turns the// text a visitor sent into a case, and the case then chooses the sort order.
class Listing{ // Returns the order the text names. Returns `Core\Arr::Order::Asc` for any other // text, so a visitor cannot send something the sort has no answer for. public static function order(string $wanted): Core\Arr::Order { return match ($wanted) { 'desc' => Core\Arr::Order::Desc, default => Core\Arr::Order::Asc, }; }}
array<int> $prices = [30, 10, 20];Core\Arr::Order $order = Listing::order('desc');
// This prints 30, 20 and 10.foreach (Core\Arr::sort($prices, { order: $order }) as int $p) { echo $p, "\n";}
// A case of a `Core` enum is compared with `==`. This prints `largest first`.echo $order == Core\Arr::Order::Desc ? 'largest first' : 'smallest first', "\n";302010largest firstA number where a case is needed
<?nvs// Shows that a method which needs a `Core` enum does not take a number. This// call does not compile. Write `Core\Arr::Order::Desc` instead of `1`.// proof: compile-error
array<int> $scores = [3, 1, 2];
echo Core\Arr::count(Core\Arr::sort($scores, { order: 1 })), "\n";error[E0401]: expected `Core\Arr::Order`, found `int` --> 04-a-number-where-a-case-is-needed.nvs:8:55 |8 | echo Core\Arr::count(Core\Arr::sort($scores, { order: 1 })), "\n"; | ^ this is `int`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A number where a Core method needs a Core enum is the error E0401, such as { order: 1 } for Core\Arr::sort. A case of another enum is E0401 too. Core\Arr::Order::Desc passed to Core\Decimal::divideRounded needs a Core\RoundMode, so it does not compile.
A case the enum does not have, such as Core\Arr::Order::Random, is the error E0405.
7 as Core\Arr::Order throws a RuntimeError when no case has the number 7. The message names every case: ` 7 is not one of Core\Arr::Order::Asc, Core\Arr::Order::Desc . 7 as ?Core\Arr::Order gives null`.
A case of one Core enum compared with a case of another is the error E0466.
use Core\Arr; lets you write Arr::Order::Desc. use Core\Arr::Order; is the error E0212, because an import names a class and not the enum inside it.
You may declare your own enum named Order. It is a different enum from Core\Arr::Order.
Core\Json::encode and Core\Debug::dump write a case of a Core enum as its number.
Do and don’t
Section titled “Do and don’t”- Do use an enum for a fixed set of choices, such as a status or a mode.
- Do use
as ?Statusfor a number from outside the program. You then handlenull. - Do use an
array<Status, T>for a value per case, such as a label. Its keys are the cases. - Do write a
matcharm for every case. Add adefaultarm only when you want one answer for all the other cases. - Do put a method that reads the case in the enum body.
$thisis the case. - Don’t try to store a value in a case. An enum has no properties. Use a class for state.
- Do give an enum inside a class a short name, such as
Status. The class name already says what it is for.
