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

后端 未结 6 1081
清歌不尽
清歌不尽 2020-12-24 00:43

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 c

6条回答
  •  时光取名叫无心
    2020-12-24 01:33

    Unfortunately not... a constant is exactly what it says on the tin, constant. Once defined it can't be redefined, so in that way, it is impossible to require its definition through PHP's abstract inheritance or interfaces.

    However... you could check to see if the constant is defined in the parent class's constructor. If it doesn't, throw an Exception.

    abstract class A
    {
        public function __construct()
        {
            if (!defined('static::BLAH'))
            {
                throw new Exception('Constant BLAH is not defined on subclass ' . get_class($this));
            }
        }
    }
    
    class B extends A
    {
        const BLAH = 'here';
    }
    
    $b = new B();
    

    This is the best way I can think of doing this from your initial description.

提交回复
热议问题