Abstract Constants In PHP - Force A Child Class To Define A Constant
Answer : 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 ...