Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Class Constants With Different Types

<?php

class A {
    protected const int|string|X C = 1;
}

class B extends A {
    protected const int|string|Y C = 'a';
}

With PHP, it is possible to have a class constant with different values, between a parent class, and its child class.

Quiz of the day : can you make a class constant with different types? Optionally different values.

Works on PHP 8.3. Application unknown.

The trick is to use union types, which allows adding new valid types without ascendant compatibility.

See Also

PHP Features

Last updated: 10 September 2026