Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 147 ยท Object-Oriented PHP

Class Constants and Enums

Learn PHP class constants, typed and final constants, and enums - pure and backed cases, methods, interfaces, cases(), from() and tryFrom() with examples.

Some values in a program never change: the maximum length of a username, the version of a file format, the tax rate your shop uses this year. Other values come from a small, fixed list: an order is pending, paid, shipped or cancelled, and nothing else. PHP gives you a tool for each. Class constants attach fixed values to a class, and enums (added in PHP 8.1) let you define a type whose only possible values are the cases you list.

Before enums, PHP code modeled fixed lists with strings or integer constants, like const STATUS_PAID = 'paid';. That works until somebody passes 'payed' or 42 where a status was expected and nothing stops them. An enum turns "one of these four statuses" into a real type that PHP checks for you. This lesson covers class constants first (including PHP 8.3's typed constants), then pure enums, backed enums, and everything you can put inside an enum.

You should already be comfortable with classes, interfaces and static members. Global constants created with define() and const are covered in Constants.

Class constants

A class constant is declared with const inside a class body. You read it with the class name, the scope resolution operator :: and the constant name. Inside the class, self:: refers to the current class:

PHP Declaring and reading class constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A few rules worth remembering:

  • Constants belong to the class, not to objects. There's one MIN_LENGTH no matter how many Password objects exist. You can still read it through an object ($object::MIN_LENGTH) or a class name stored in a variable.
  • Visibility works like it does for methods. public constants are readable everywhere, protected ones in the class and its children, private ones only in the class itself. Without a keyword, a constant is public.
  • The value must be a constant expression: literals, arrays, other constants, arithmetic on them and (since PHP 8.1) enum cases. You can't call a function like strlen() in a constant initializer.
  • Constant names are case-sensitive and by convention written in UPPER_SNAKE_CASE.

Every class also has a built-in ::class constant that holds its fully qualified name as a string. You'll see Password::class everywhere in modern code, especially once you use namespaces.

Constants in inheritance: self:: versus static::

Child classes inherit constants and can redefine them. Which value you get depends on how you refer to the constant. self::NAME always means "the constant in the class where this code is written". static::NAME uses late static binding: it means "the constant in the class that was actually called".

PHP self and static with inherited constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is self says email, then static says sms, then sms. If a parent class wants children to customize a constant, the parent must read it with static::.

Final constants and interface constants (PHP 8.1)

Sometimes a value must never be redefined in a child class. Mark it final (PHP 8.1+) and any attempt to override it is a compile-time fatal error:

PHP
class Protocol
{
    final public const VERSION = 3;
}

class CustomProtocol extends Protocol
{
    public const VERSION = 4; // Fatal error: CustomProtocol::VERSION cannot override final constant Protocol::VERSION
}

Interfaces can declare constants too, and every implementing class gets them. Since PHP 8.1 implementing classes may override interface constants unless the interface marks them final.

Typed class constants (PHP 8.3)

Since PHP 8.3 you can declare a type for a class constant, just like a typed property. The type is checked when the class is compiled, and it is enforced for child classes that redefine the constant, which is where it matters most:

PHP Typed class constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If a child class wrote const int MAX_ITEMS = 'many';, PHP would refuse to compile it with Cannot use string as value for class constant Cart::MAX_ITEMS of type int. Typed constants make the contract between a parent and its children explicit. The usual type coercion rules don't apply here: the value must already have the right type (an int is still accepted for a float constant).

Pure enums

An enum declares a new type with a fixed set of possible values called cases. A pure enum has cases with no underlying value:

PHP
enum Suit
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}

Each case is a singleton object of type Suit. Suit::Hearts is always the same object, so you compare cases with ===. And because Suit is a type, a function can demand one:

PHP A pure enum as a parameter type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line fails on purpose. Passing the string 'Hearts' throws a TypeError: color(): Argument #1 ($suit) must be of type Suit, string given. That's the whole point: with an enum, invalid values can't sneak in.

Notice how well enums pair with match. match compares with ===, so it works directly on cases. If you add a fifth case later and forget to handle it, match throws an UnhandledMatchError instead of quietly returning nothing, which makes the bug easy to find.

Every case has a read-only name property holding the case name as a string. Enum cases are objects, but they're special:

  • You can't create them with new and you can't clone them.
  • They have no state: enums can't declare properties (other than the built-in name and value).
  • Case names follow the same rules as constants. The PHP documentation and most code use PascalCase for them.

Backed enums

Pure enums are perfect inside your program, but data often has to leave it: you store a status in a database column, put it in JSON or read it from a form. A backed enum gives every case a scalar value, either all int or all string:

PHP
enum Status: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Cancelled = 'cancelled';
}

Backed cases have an extra read-only value property. Going the other way, from a stored value back to a case, uses two static methods every backed enum gets automatically:

  • Status::from('paid') returns Status::Paid, or throws a ValueError if no case has that value.
  • Status::tryFrom('paid') returns Status::Paid, or null if no case matches.
PHP Backed enums with from and tryFrom

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Use from() when a bad value means something is genuinely broken (a corrupted database row), and tryFrom() when bad values are expected (user input). Notice that matching is exact: 'PAID' is not 'paid'.

json_encode() turns a backed case into its value, so the JSON contains "status":"paid". A pure enum can't be encoded at all: json_encode() fails and returns false (or throws a JsonException with JSON_THROW_ON_ERROR), because there is no value to write.

Some other rules for backed enums:

  • All cases must have the same backing type and unique values.
  • The values must be literals or constant expressions, not function calls.
  • An int enum looks like enum Priority: int { case Low = 1; ... }.

cases(): listing every case

Every enum has a static cases() method that returns all cases in declaration order. It's perfect for building select menus, validating input or writing tests:

PHP Building options from cases()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last loop prints HTML <option> tags as plain text here. On a web server inside a <select>, the browser would render them as a drop-down with "Medium" preselected.

Methods, interfaces and constants in enums

Enums are much more than lists of names. They can have methods (both instance and static), implement interfaces, declare constants and use traits (as long as the trait has no properties). Inside an instance method, $this is the current case:

PHP An enum with methods, an interface and a constant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This is the real power of enums: the rules about statuses live with the statuses. Instead of if ($status === 'paid' || $status === 'pending') scattered across a dozen files, you call $status->canTransitionTo($next) and the knowledge sits in one place.

A constant in an enum can refer to a case (const DEFAULT = self::Pending;), which is a handy way to give a case a second name. Since PHP 8.2 you can also use enum properties in constant expressions, for example const DEFAULT_VALUE = self::Pending->value;.

Enums versus class constants

Both look similar at first, so here's how to choose:

Use When
Class constant A single fixed value: a limit, a default, a version number, a configuration key.
Pure enum A closed set of options used only inside your code: card suits, directions, log levels.
Backed enum A closed set of options that's stored or transmitted: order statuses, user roles, HTTP methods.

The rule of thumb: if you would write a group of constants with a shared prefix like ROLE_ADMIN, ROLE_EDITOR, ROLE_VIEWER, you want an enum.

Type-hint parameters as the enum (Role $role), not as string. Convert to and from the backing value only at the edges of your program: when reading a request, a database row or a JSON payload, and when writing them back.

Common mistakes

  • Comparing a case with its value. Status::Paid === 'paid' is false, because a case is an object. Compare $status === Status::Paid, or $status->value === 'paid' if you really have a string.
  • Using from() on user input. It throws on unknown values. Use tryFrom() and handle null.
  • Trying to add state. enum Color { public string $hex; } is a fatal error. Put data in a method (public function hex(): string { return match ($this) { ... }; }) or a constant.
  • Using an enum case as an array key. $counts[Suit::Hearts] throws TypeError: Cannot access offset of type Suit on array. Use $suit->name or $suit->value as the key, or an SplObjectStorage.
  • Forgetting that match must be exhaustive. That's a feature: an unhandled case throws immediately instead of silently doing nothing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A parent class reads self::LIMIT and a child class redefines LIMIT. What does the parent method return when called on a child object?

    self:: always refers to the class where the code is written. To get the child's value, the parent must use static::LIMIT (late static binding).
  2. 2. What does Status::tryFrom('unknown') return for a backed enum with no matching case?

    tryFrom() returns null when no case matches. from() is the variant that throws a ValueError.
  3. 3. Given enum Suit { case Hearts; }, what is Suit::Hearts === Suit::Hearts?

    Each enum case is a singleton, so the identity comparison is true. This is why match and in_array(..., true) work well with enums.
  4. 4. Which of these is NOT allowed in a PHP enum?

    Enums can't declare properties; their only properties are the built-in read-only name (and value for backed enums). Methods, interfaces and constants are all allowed.
  5. 5. What does echo json_encode(["s" => Status::Paid]); print for enum Status: string { case Paid = "paid"; }?

    json_encode() writes a backed enum case as its value, so the result contains "paid". Encoding a pure enum case would fail, because it has no value.

Summary

  • Class constants (const NAME = value;) attach fixed values to a class. Read them with ClassName::NAME, self::NAME or static::NAME; they support public, protected and private.
  • self:: reads the constant of the class the code is written in; static:: reads the redefined value of the class actually called.
  • final constants (8.1) can't be overridden, and typed constants (8.3) such as const int MAX = 10; enforce a type, including in child classes.
  • Pure enums (8.1) define a type with a fixed set of cases. Cases are singletons: compare them with === and handle them with match.
  • Backed enums (enum Status: string) give each case a value. Convert stored data with from() (throws ValueError) or tryFrom() (returns null).
  • cases() lists every case; enums can have methods, constants, static methods and interfaces, but no properties.
  • Use enums for closed sets of options instead of groups of prefixed string or integer constants.

Next: Readonly Properties and Immutable Objects