Chapter 3. Other Features of Hack

Hack has four major features that make the language different from PHP in fundamental ways: typechecking, collections, asynchronous (async) functions, and XHP. Beyond those, though, there’s a wide range of smaller features that are designed to simplify certain common patterns or to address minor gaps.

Enums

An enum (short for enumeration) is a collection of related constants. Unlike simply creating global constants or class constants, creating an enum results in a new type: you can use the names of enums in type annotations. They also offer functionality like getting an array of all valid names or values, without resorting to heavyweight reflection APIs.

The syntax for an enum is the keyword enum, followed by a name for the enum, then a colon, then either int or string (which will be the enum’s underlying type), then a brace-enclosed, semicolon-separated list of enum members. Each member is a name, followed by an equals sign and then a value (which must match the enum’s underlying type):

enum CardSuit : int {
  SPADES = 0;
  HEARTS = 1;
  CLUBS = 2;
  DIAMONDS = 3;
}

Enum names have the same restrictions as class names (with regard to what characters they may contain, etc.), and it’s an error to have a class and an enum with the same name.

The names of enum members have the same restrictions as class constant names. The names must be unique within the enum; if there are two members with the same name, the typechecker will report an error, and HHVM will ...

Get Hack and HHVM now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.