Inheritance of static members in PHP

后端 未结 3 1475
走了就别回头了
走了就别回头了 2020-12-02 18:25

In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class. But I\'m wondering if there\'s any way around this.

I\'m try

3条回答
  •  盖世英雄少女心
    2020-12-02 19:21

    The forthcoming PHP 5.3.0 release includes late static binding, which might help. Using this feature you could use a static variable inside a static method, and let the late static binding take care of finding the "right" method.

    class Foo {
        public static function getDefault() {
            static $default = 'DEFAULT';
            return $default;
        }
        public static function doSomething ($param) {
            $default=static::getDefault(); // here is the late static binding
            $param = ($param === FALSE) ? $default : $param;
            return $param;
    
        }
    }
    
    class Bar extends Foo {
         public static function getDefault() {
            static $default = 'NEW DEFAULT FOR CHILD CLASS';
            return $default;
        }
    }
    

提交回复
热议问题