rfc:allow-constant-override-consistently

PHP RFC - Consistent class-constant override

Introduction

Currently, a class constant can be overridden in inheritors, but it's disallowed in interfaces.

// The following works:
class A1                { const X = 1; }
class B1 extends A1     { const X = 2; }
 
// This doesn't:
interface A2            { const X = 1; }
interface B2 extends A2 { const X = 2; }
 
// This doesn't work either:
interface A3            { const X = 1; }
class B3 implements A3  { const X = 2; }

Even if this restriction had a purpose, it's not really effective since it has only effect in direct inheritors:

// This works:
interface A3                    { const X = 1; }
abstract class B3 implements A3 { } // Can't override here
class B4 extends B3             { const X = 2; } // But can do here

Proposal

This RFC proposes to normalize the behavior so that constant override is allowed everywhere. This is not an invite at reckless overriding but simply a matter of consistency. Class constants are constants only within the class they are defined in; child classes inherit them by default but the user can optionally override them if desired.

Backward Incompatible Changes

None.

Proposed PHP Version:

7.3

Future scope:

If desired by the community, the 'final' keyword could be introduced in order to actually prevent constant override.

Voting

2/3 majority will be required.

References

rfc/allow-constant-override-consistently.txt · Last modified: 2018/04/14 04:56 by wesnetmo