phpconstantsabstract

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


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) ?


Solution

  • A constant is a constant; there is no abstract constants in PHP as far as I know, but you can have a work around:

    Sample Abstract Class

    abstract class Hello {
        const CONSTANT_1 = 'abstract'; // Make Abstract
        const CONSTANT_2 = 'abstract'; // Make Abstract
        const CONSTANT_3 = 'Hello World'; // Normal Constant
        function __construct() {
            Enforcer::__add(__CLASS__, get_called_class());
        }
    }
    

    This would run fine

    class Foo extends Hello {
        const CONSTANT_1 = 'HELLO_A';
        const CONSTANT_2 = 'HELLO_B';
    }
    new Foo();
    

    Bar would return Error

    class Bar extends Hello {
        const CONSTANT_1 = 'BAR_A';
    }
    new Bar();
    

    Songo would return Error

    class Songo extends Hello {
    
    }
    new Songo();
    

    Enforcer Class

    class Enforcer {
        public static function __add($class, $c) {
            $reflection = new ReflectionClass($class);
            $constantsForced = $reflection->getConstants();
            foreach ($constantsForced as $constant => $value) {
                if (constant("$c::$constant") == "abstract") {
                    throw new Exception("Undefined $constant in " . (string) $c);
                }
            }
        }
    }