Typed class constants and constant expressions

suggest change

Class constants were untyped for most of PHP's history. A subclass could replace const VERSION = '1.0' with const VERSION = 2, and nothing would complain until some code got an int where it expected a string. Constant initializers were also limited: arithmetic, strings, arrays and other constants were allowed, but not much else.

Over the PHP 8 releases these features were added:

Version Feature
8.1 final class constants, interface constants can be overridden, new in initializers (not in class constants)
8.2 -> on enum cases in constant expressions (Status::Active->value)
8.3 typed class constants (const string NAME = ...), dynamic fetch Foo::{$name}
8.4 #[\Deprecated] on class constants
8.5 static closures, first-class callables and casts in constant expressions, attributes on global constants

This article covers each of them. The examples need PHP 8.3, and the sections marked 8.5 need PHP 8.5.

Related topics: Class Constants, Defining constants, Enums, Named and optional parameters and Attributes.

Typed class constants

Since PHP 8.3 you can declare a type between const and the constant's name, the same way you would for a property:

<?php
class Config
{
    const string NAME = 'app';
    const int MAX_RETRIES = 3;
    const float RATIO = 1.5;
    const bool DEBUG = false;
    const array LEVELS = ['info', 'warn'];
    const ?string PREFIX = null;
    const int|string ID = 'x1';
    const float TIMEOUT = 3; // an int is accepted for a float
}

var_dump(Config::NAME, Config::PREFIX, Config::TIMEOUT);

$c = new ReflectionClassConstant(Config::class, 'ID');
var_dump($c->hasType(), (string) $c->getType());

Output:

string(3) "app"
NULL
float(3)
bool(true)
string(10) "string|int"

The value has to match the declared type. The check is always strict, even without declare(strict_types=1). The one conversion allowed is int to float, the same as for typed properties in strict mode:

<?php
class Bad
{
    const string NAME = 1;
}

Output:

Fatal error: Cannot use int as value for class constant Bad::NAME of type string in ... on line 4

Most types that are valid for properties are valid here too: scalars, array, iterable, mixed, object, class and enum names, nullable types, and union, intersection and DNF types. Three are not:

<?php
class Handlers
{
    const callable ON_ERROR = 'error_log';
}

Output:

Fatal error: Class constant Handlers::ON_ERROR cannot have type callable in ... on line 4

Use Closure instead: as shown later, PHP 8.5 lets a constant hold a closure.

When the check happens

If the compiler can work out the value while compiling, a mismatch is a compile-time fatal error, like the one above. If the initializer refers to a constant from another class, PHP evaluates it the first time the constant is used. A mismatch then throws a TypeError that you can catch:

<?php
class Limits
{
    const int MAX = Defaults::MAX;
}

class Defaults
{
    const string MAX = 'ten';
}

echo "classes declared\n";

try {
    echo Limits::MAX, "\n";
} catch (TypeError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

Output:

classes declared
TypeError: Cannot assign string to class constant Limits::MAX of type int

self, static and enum types

A constant can use a class or enum as its type. This is most useful with enums, because enum cases are the only objects allowed in a class constant (see below):

<?php
enum Status
{
    case Active;
    case Disabled;

    const self DEFAULT = self::Active;
}

class Account
{
    const Status INITIAL = Status::DEFAULT;

    public function __construct(public Status $status = self::INITIAL) {}
}

var_dump(Status::DEFAULT);
var_dump((new Account())->status);

Output:

enum(Status::Active)
enum(Status::Active)

static is accepted as a type too, but in practice it only fits enum cases, since a plain class constant can't hold an instance of its own class.

Types and inheritance

Once a parent gives a constant a type, every override must have a compatible type. The rule is covariance, the same as for return types: a child may narrow the type, but not widen it or remove it.

<?php
interface HasVersion
{
    const string VERSION = '1.0';
}

class Plugin implements HasVersion
{
    const string VERSION = '2.0'; // same type: OK
}

class Base
{
    const int|string CODE = 'unknown';
}

class Child extends Base
{
    const int CODE = 42; // narrower type: OK
}

echo Plugin::VERSION, "\n";
echo Child::CODE, "\n";

Output:

2.0
42

Widening the type, or leaving it out, is a compile-time error:

<?php
class Base
{
    const string NAME = 'base';
}

class Child extends Base
{
    const NAME = 'child';
}

Output:

Fatal error: Type of Child::NAME must be compatible with Base::NAME of type string in ... on line 7

Going the other way is allowed: a child can add a type to a constant that was untyped in the parent. So you can add types to your own classes gradually, starting with the base classes and interfaces that define a contract.

Typing constants matters most in interfaces and abstract classes, where a constant is part of a contract that subclasses fill in:

<?php
interface Exporter
{
    const string EXTENSION = '';
    const string MIME_TYPE = '';
}

final class CsvExporter implements Exporter
{
    const string EXTENSION = 'csv';
    const string MIME_TYPE = 'text/csv';
}

final class JsonExporter implements Exporter
{
    const string EXTENSION = 'json';
    const string MIME_TYPE = 'application/json';
}

function describe(Exporter $e): string
{
    // static analysis and readers know these are strings
    return $e::EXTENSION . ' => ' . $e::MIME_TYPE;
}

echo describe(new CsvExporter()), "\n";
echo describe(new JsonExporter()), "\n";

Output:

csv => text/csv
json => application/json

Notice $e::EXTENSION: you can read a constant through an object, and late static binding picks the constant of the object's actual class.

Final class constants

Before PHP 8.1, class constants could always be overridden, while interface constants could never be overridden. PHP 8.1 made both work the same: interface constants can now be overridden, and either kind can be marked final to prevent it:

<?php
class Base
{
    final public const string API = 'v1';
}

class Child extends Base
{
    public const string API = 'v2';
}

Output:

Fatal error: Child::API cannot override final constant Base::API in ... on line 7

The same applies to interfaces:

<?php
interface Codec
{
    final const string FORMAT = 'json';
}

class XmlCodec implements Codec
{
    const string FORMAT = 'xml';
}

Output:

Fatal error: XmlCodec::FORMAT cannot override final constant Codec::FORMAT in ... on line 7

A few rules:

Use final for values that other code relies on being exact, such as a protocol version or a binary format's magic bytes. A subclass that changes one of those breaks callers. Leave constants overridable when they are meant to be customized, like EXTENSION in the exporter example above.

See Final Keyword for final classes and methods.

Dynamic constant fetch: Foo::{$name}

Before PHP 8.3, reading a class constant whose name is in a variable required constant() with a string:

$value = constant(Http::class . '::' . $name);

PHP 8.3 added Foo::{expr} syntax for this, matching $obj->{$name} for properties and Foo::{$name}() for methods:

<?php
class Http
{
    const int OK = 200;
    const int NOT_FOUND = 404;
}

$name = 'NOT_FOUND';
echo Http::{$name}, "\n";
echo Http::{'O' . 'K'}, "\n";

$class = 'Http';
echo $class::{$name}, "\n";

// the pre-8.3 way still works
echo constant("Http::$name"), "\n";

try {
    echo Http::{'MISSING'};
} catch (Error $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    $code = 404;
    echo Http::{$code};
} catch (TypeError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

Output:

404
200
404
404
Error: Undefined constant Http::MISSING
TypeError: Cannot use value of type int as class constant name

Watch out for visibility

A dynamic fetch follows normal visibility rules. That means code inside the class can read private constants too. If the name comes from user input, that can leak values you didn't mean to expose:

<?php
final class Http
{
    public const int OK = 200;
    public const int TEAPOT = 418;
    private const string SECRET = 'internal';

    public static function unsafeCode(string $name): mixed
    {
        $name = strtoupper($name);
        return defined("self::$name") ? self::{$name} : null;
    }

    public static function code(string $name): ?int
    {
        $name = strtoupper($name);
        if (!defined("self::$name")) {
            return null;
        }
        $c = new ReflectionClassConstant(self::class, $name);
        return $c->isPublic() ? $c->getValue() : null;
    }
}

var_dump(Http::unsafeCode('teapot'));
var_dump(Http::unsafeCode('secret')); // leaks a private constant

var_dump(Http::code('teapot'));
var_dump(Http::code('secret'));
var_dump(Http::code('gone'));

Output:

int(418)
string(8) "internal"
int(418)
NULL
NULL

When the set of valid names is small and fixed, a backed enum with tryFrom() is usually a better fit than looking up constants by name.

What a constant expression can contain

Class constants, property defaults, parameter defaults, static variable initializers, global const declarations and attribute arguments all take a constant expression: an expression PHP can evaluate without running any of your code at that point.

These are allowed in every one of those places:

Here is a class that uses most of them:

<?php
enum Env: string
{
    case Prod = 'prod';
    case Dev = 'dev';
}

const BASE_DIRS = ['src', 'tests'];

class Settings
{
    const ?string OVERRIDE = null;
    const string NAME = self::OVERRIDE ?? 'default';
    const int KB = 1 << 10;
    const int MB = self::KB ** 2;
    const bool BIG = self::MB > 1_000_000;
    const string SIZE = self::BIG ? 'big' : 'small';
    const array DIRS = [...BASE_DIRS, 'docs'];
    const string ENV = Env::Prod->value;
    const array LOG_LEVELS = [Env::Dev->value => 'debug', Env::Prod->value => 'error'];
    const string LOG_LEVEL = self::LOG_LEVELS[self::ENV];
    const string ENUM_CLASS = Env::class;
    const int BITS = PHP_INT_SIZE * 8;
}

foreach ((new ReflectionClass(Settings::class))->getConstants() as $name => $value) {
    echo str_pad($name, 10), ' = ', json_encode($value), "\n";
}

Output:

OVERRIDE   = null
NAME       = "default"
KB         = 1024
MB         = 1048576
BIG        = true
SIZE       = "big"
DIRS       = ["src","tests","docs"]
ENV        = "prod"
LOG_LEVELS = {"dev":"debug","prod":"error"}
LOG_LEVEL  = "error"
ENUM_CLASS = "Env"
BITS       = 64

These are still not allowed:

Expression Error
const X = strlen('a'); Constant expression contains invalid operations
const X = $config; Constant expression contains invalid operations
const X = $a instanceof Foo; Constant expression contains invalid operations
const X = static::class; static::class cannot be used for compile-time class name resolution
const X = new Foo(); (class constant) New expressions are not supported in this context
const X = (object) []; Object casts are not supported in this context

The rule of thumb: you can't call anything or read a variable. A first-class callable such as strlen(...) is allowed because it creates a closure without calling the function.

If you need a value computed by a function, use a static method, a static property set during bootstrap, or a global constant made with define(), which takes any expression at runtime (see Class Constants).

Objects with new in initializers (PHP 8.1)

PHP 8.1 allowed new in parameter defaults, static variable initializers, global constants and attribute arguments. It is not allowed in class constants or property defaults. Those are evaluated once per class, and sharing one mutable object between every instance would be surprising.

<?php
final class Money
{
    public function __construct(
        public int $cents = 0,
        public string $currency = 'EUR',
    ) {}
}

// global constant
const ZERO = new Money();
echo ZERO->cents, ' ', ZERO->currency, "\n";

// parameter default: a new object on every call that omits the argument
function format(Money $m = new Money(100, 'USD')): string
{
    return number_format($m->cents / 100, 2) . ' ' . $m->currency;
}
echo format(), "\n";

// static variable initializer
function requestCount(): int
{
    static $seen = new ArrayObject();
    $seen[] = true;
    return count($seen);
}
requestCount();
requestCount();
echo requestCount(), "\n";

Output:

0 EUR
1.00 USD
3

ZERO holds an object, and the object is still mutable: ZERO->cents = 5 would work unless Money is readonly. Use a readonly class for objects stored in constants. The Named and optional parameters article covers new in parameter defaults in more detail.

Closures and first-class callables in constants (PHP 8.5)

PHP 8.5 allows static closures and first-class callables in constant expressions. A constant can now hold a small function, which is handy for lookup tables of strategies:

<?php
class Normalize
{
    const Closure TRIM = static function (string $s): string {
        return trim($s);
    };
    const Closure UPPER = strtoupper(...);
    const Closure SLUG = static function (string $s): string {
        return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($s)), '-');
    };

    const array PIPELINE = [self::TRIM, self::UPPER];
}

$v = '  hello world ';
foreach (Normalize::PIPELINE as $step) {
    $v = $step($v);
}
var_dump($v);

echo (Normalize::SLUG)('  Typed Class Constants!  '), "\n";
var_dump(Normalize::TRIM === Normalize::TRIM);

Output:

string(11) "HELLO WORLD"
typed-class-constants
bool(true)

There are restrictions, each with its own error:

Code Error
const T = function ($s) { ... }; Closures in constant expressions must be static
const T = static function ($s) use ($x) { ... }; Cannot use(...) variables in constant expression
const T = static fn($s) => trim($s); Constant expression contains invalid operations

So the closure must be static (it has no $this), it can't capture variables, and arrow functions aren't supported. Inside the body you can call anything you like. The body runs when the closure is called, not when the constant is evaluated.

The same rules apply to parameter defaults and attribute arguments. Attribute arguments are where this matters most, because before 8.5 you couldn't attach behavior to an attribute without naming a method in a string:

<?php
#[Attribute(Attribute::TARGET_PROPERTY)]
final class Validate
{
    public function __construct(public Closure $check) {}
}

final class SignupForm
{
    #[Validate(static function (string $v): bool { return str_contains($v, '@'); })]
    public string $email = '';

    #[Validate(is_numeric(...))]
    public string $age = '';
}

function sortedCopy(array $a, Closure $cmp = static function ($x, $y) { return $x <=> $y; }): array
{
    usort($a, $cmp);
    return $a;
}

$input = ['email' => 'ada@example.com', 'age' => 'forty'];
foreach ((new ReflectionClass(SignupForm::class))->getProperties() as $prop) {
    $check = $prop->getAttributes(Validate::class)[0]->newInstance()->check;
    $value = $input[$prop->getName()];
    echo $prop->getName(), ': ', $check($value) ? 'valid' : 'invalid', "\n";
}

echo implode(', ', sortedCopy([3, 1, 2])), "\n";

Output:

email: valid
age: invalid
1, 2, 3

See Attributes for how to read attributes with reflection.

Casts in constant expressions (PHP 8.5)

PHP 8.5 also allows the scalar and array casts in constant expressions. This is useful when a value comes from another constant with the wrong type, such as a global constant defined as a string:

<?php
const PORT = '8443';

class Server
{
    const int PORT = (int) PORT;
    const string LABEL = 'port ' . (string) self::PORT;
    const bool TLS = (bool) '1';
    const float LIMIT = (float) '1.5e3';
    const array HOSTS = (array) 'localhost';
}

var_dump(Server::PORT, Server::LABEL, Server::TLS, Server::LIMIT, Server::HOSTS);

Output:

int(8443)
string(9) "port 8443"
bool(true)
float(1500)
array(1) {
  [0]=>
  string(9) "localhost"
}

Without the (int) cast, const int PORT = PORT; would be a type error, because typed constants don't coerce strings to ints. Casts are explicit, so they are allowed. (object) is the one cast that is still rejected.

Attributes on global constants (PHP 8.5)

Attributes could already be placed on class constants. PHP 8.5 extends them to global constants declared with const, and adds Attribute::TARGET_CONSTANT for attribute classes. The most useful built-in one is #[\Deprecated]. It works on class constants since 8.4 and on global constants since 8.5:

<?php
#[\Deprecated('use NEW_API_URL', since: '2.0')]
const OLD_API_URL = 'http://api.example.com';
const NEW_API_URL = 'https://api.example.com';

class Api
{
    #[\Deprecated('use Api::TIMEOUT_MS', since: '3.1')]
    const int TIMEOUT = 30;
    const int TIMEOUT_MS = 30_000;
}

echo OLD_API_URL, "\n";
echo Api::TIMEOUT, "\n";

$r = new ReflectionConstant('OLD_API_URL');
var_dump($r->isDeprecated());

Output:

Deprecated: Constant OLD_API_URL is deprecated since 2.0, use NEW_API_URL in ... on line 13
http://api.example.com

Deprecated: Constant Api::TIMEOUT is deprecated since 3.1, use Api::TIMEOUT_MS in ... on line 14
30
bool(true)

This lets you rename a constant without breaking callers: keep the old name, mark it deprecated, and remove it in the next major version.

Your own attributes can target constants as well:

<?php
#[Attribute(Attribute::TARGET_CONSTANT)]
final class FromEnv
{
    public function __construct(public string $variable) {}
}

#[FromEnv('APP_TIMEOUT')]
const TIMEOUT = 30;

#[FromEnv('APP_HOST')]
const HOST = 'localhost';

foreach (['TIMEOUT', 'HOST'] as $name) {
    $r = new ReflectionConstant($name);
    $attr = $r->getAttributes(FromEnv::class)[0]->newInstance();
    $value = getenv($attr->variable);
    echo $name, ': ', $value === false ? var_export($r->getValue(), true) . ' (default)' : $value, "\n";
}

Output:

TIMEOUT: 30 (default)
HOST: 'localhost' (default)

Two limitations:

Guidelines

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents