Skip to content

10: Override Attributes on Constants and Enum Cases

Use #[Override] to catch a renamed protocol constant or enum case. The engine checks that the name matches a constant on a parent class or interface.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable override-constants.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/10-override-constants/override-constants.php
override-constants.php
<?php
declare(strict_types=1);
class VersionOne
{
public const int VERSION = 1;
}
final class VersionTwo extends VersionOne
{
#[Override]
public const int VERSION = 2;
}
interface ServiceState
{
public const Ready = 'ready';
}
enum WorkerState: string implements ServiceState
{
#[Override]
case Ready = 'ready';
}
echo 'Version ', VersionTwo::VERSION, PHP_EOL;
echo WorkerState::Ready->value, PHP_EOL;
Version 2
ready

A backed enum case can implement an interface constant of the same name, subject to the usual constant override rules. A missing target is a compile-time error. Apply the attribute at the point where you intend to keep the inherited contract.

Change VersionTwo::VERSION to REVISION in a copy while keeping the attribute. Run php -l and confirm PHP rejects the declaration.

Continue with Customize Enum Dumps with __debugInfo().