Class inheritance in PHP 5.2: Overriding static variable in extension class?

后端 未结 3 1531
眼角桃花
眼角桃花 2021-02-20 02:53

I need to bea be able to use a static variable set in a class that extends a base class... from the base class.

Consider this:

class Animal {
    public          


        
3条回答
  •  难免孤独
    2021-02-20 03:09

    I ran into this problem when subclassing something in the Zend Framework. My determination was that in purely static land, you only have one option... Redefine the function in the inheriting class:

    class Animal {
        public static $color = 'black';
    
        public static function get_color()
        {
            return self::$color;
        }
    }
    
    class Dog extends Animal {
        public static $color = 'brown';
    
        public static function get_color() 
        {
          return self::$color;
        }
    }
    

    If you are able to create instances - You can use get_class($this) to find out the calling class, for example:

    class Animal {
        public static $color = 'black';
    
        public function getColor() // note, not static
        {
          $class = get_class($this);
          return $class::$color;
        }
    }
    
    class Dog extends Animal {
        public static $color = 'brown';
    }
    
    $animal = new Animal();
    echo $animal->getColor(); // prints 'black'
    $dog = new Dog();
    echo $dog->getColor(); // prints 'brown'
    

    The only other option I thought of was using a function parameter to the static function to define a class it was being called from. It can default to __CLASS__ and then you can return parent::get_class($class) from the subclass. A pattern like this could be used to make re-using the static function easier (as I doubt returning a public static property is the only thing you are trying to use self:: for in that static method:

    class Animal {
        public static $color = 'black';
    
        public static function get_color($class = __CLASS__)
        {
            // Super Simple Example Case... I imagine this function to be more complicated
            return $class::$color;
        }
    }
    
    class Dog extends Animal {
        public static $color = 'brown';
    
        public static function get_color($class = __CLASS__)
        {
          return parent::get_color($class);
        }
    }
    

提交回复
热议问题