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

后端 未结 6 1085
清歌不尽
清歌不尽 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:35

    No, yet you could try other ways such as abstract methods:

    abstract class Fruit
    {
        abstract function getName();
        abstract function getColor();
    
        public function printInfo()
        {
            echo "The {$this->getName()} is {$this->getColor()}";
        }
    }
    
    class Apple extends Fruit
    {
        function getName() { return 'apple'; }
        function getColor() { return 'red'; }
    
        //other apple methods
    }
    
    class Banana extends Fruit
    {
        function getName() { return 'banana'; }
        function getColor() { return 'yellow'; }
    
        //other banana methods
    }  
    

    or static members:

    abstract class Fruit
    {
        protected static $name;
        protected static $color;
    
        public function printInfo()
        {
            echo "The {static::$name} is {static::$color}";
        }
    }
    
    class Apple extends Fruit
    {
        protected static $name = 'apple';
        protected static $color = 'red';
    
        //other apple methods
    }
    
    class Banana extends Fruit
    {
        protected static $name = 'banana';
        protected static $color = 'yellow';
    
        //other banana methods
    } 
    

    Source

提交回复
热议问题