Typed Class Constants

Since PHP 8.3, a class constant may declare a type, exactly like a typed property. PHP checks the declared type against the constant’s value at compile time.

<?php
class Config {
  public const int MAX_USERS = 100;
  public const string VERSION = '1.0';
}

echo Config::MAX_USERS, "\n";
echo Config::VERSION, "\n";
?>

100 1.0
A value that does not match the declared type is a fatal compile-time error — the whole script fails before any of it runs, so this cannot be caught with try/catch.

<?php
class Config {
  public const int MAX_USERS = "one hundred"; // string, not int
}
?>

Fatal error: Cannot use string as value for class constant Config::MAX_USERS of type int in D:\xampp\htdocs\typed-class-constants-mismatch.php on line 3 Stack trace: #0 {main}
A class constant can also be fetched dynamically, using a variable that holds the constant’s name inside { } after :: — eg. Foo::{$name} — instead of writing the constant’s name literally.

<?php
class Config {
  public const MAX_USERS = 100;
  public const VERSION = '1.0';
}

$name = 'MAX_USERS';
echo Config::{$name}, "\n";

$name = 'VERSION';
echo Config::{$name}, "\n";
?>

100 1.0