Abstract constants in PHP - Force a child class to define a constant

Alex picture Alex · Apr 29, 2012 · Viewed 34k times · Source

I noticed that you can't have abstract constants in PHP.

Is there a way I can force a child class to define a constant (which I need to use in one of the abstract class internal methods) ?

Answer

WebSmithery picture WebSmithery · Mar 31, 2017

This may be a bit of a ‘hack’, but does the job with very little effort, but just with a different error message if the constant is not declared in the child class.

A self-referential constant declaration is syntactically correct and parses without problem, only throwing an error if that declaration is actually executed at runtime, so a self-referential declaration in the abstract class must be overridden in a child class else there will be fatal error: Cannot declare self-referencing constant.

In this example, the abstract, parent class Foo forces all its children to declare the variable NAME. This code runs fine, outputting Donald. However, if the child class Fooling did not declare the variable, the fatal error would be triggered.

<?php

abstract class Foo {

    // Self-referential 'abstract' declaration
    const NAME = self::NAME;

}

class Fooling extends Foo {

    // Overrides definition from parent class
    // Without this declaration, an error will be triggered
    const NAME = 'Donald';

}

$fooling = new Fooling();

echo $fooling::NAME;