MENU
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
<?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}
<?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