PHP has invested significant efforts in enhancing its type system year after year. These improvements aim to make PHP more robust, maintainable, and aligned with modern programming practices. Since PHP 8.3, it is possible to declare the type for class constants. All types are allowed, just like for properties, except void
, callable
, and never
. A type for a constant is declared by placing it after the const
keyword.
<?php
class PaginatorConst
{
public const string DEFAULT_SORT_ORDER = 'DESC';
public const int PER_PAGE = 20;
public const array SORTABLE_COLUMNS = ['id', 'name'];
}
A crucial observation is that when a parent class declares a type for constant, all subclasses are required to declare a compatible type. Not specifying the class constant type is considered as incompatible.
<?php
class PostPaginatorConst extends PaginatorConst
{
public const string DEFAULT_SORT_ORDER = 'ASC'; // OK
public const string PER_PAGE = '20'; // ERROR. Wrong type
public const SORTABLE_COLUMNS = ['id', 'price']; // ERROR. No type declared
}
Interfaces, traits, and enums also support the declaration of types for constants.
<?php
interface RequestInterface
{
public const string DEFAULT_METHOD = 'POST';
}
<?php
trait CommandTrait
{
public const int SUCCESS = 0;
public const int FAILURE = 1;
}
<?php
enum UserStatus
{
public const int TOTAL_STATUSES = 2;
}
Leave a Comment
Cancel reply