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

后端 未结 3 1533
眼角桃花
眼角桃花 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

    In PHP 5.3+, the following would be preferred:

    class Animal {
        public static $color = 'black';
    
        public static function get_color()
        {
            return static::$color; // Here comes Late Static Bindings
        }
    }
    
    class Dog extends Animal {
        public static $color = 'brown';
    }
    
    echo Animal::get_color(); // prints 'black'
    echo Dog::get_color(); // prints 'brown'
    

    Late Static Bindings (PHP.net)

提交回复
热议问题