10: Override Attributes on Constants and Enum Cases
Overview
Section titled “Overview”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.
Prerequisites
Section titled “Prerequisites”- 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.
What You’ll Build
Section titled “What You’ll Build”A runnable override-constants.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/10-override-constants/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;Expected Result
Section titled “Expected Result”Version 2readyWhy It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Change VersionTwo::VERSION to REVISION in a copy while keeping the attribute. Run php -l and confirm PHP rejects the declaration.
Wrap-up
Section titled “Wrap-up”Continue with Customize Enum Dumps with __debugInfo().