Overriding static members in derived classes in PHP

前端 未结 3 1237
Happy的楠姐
Happy的楠姐 2021-01-11 17:44


        
3条回答
  •  误落风尘
    2021-01-11 18:08

    Based on deceze's and Undolog's input: Undolog is right, for PHP <= 5.2 .

    But with 5.3 and late static bindings it will work , just use static instead of self inside the function - now it will work...//THX @ deceze for the hint

    for us copy past sample scanning stackoverflow users - this will work:

    class Base {
      protected static $c = 'base';
      public static function getC() {
        return static::$c; // !! please notice the STATIC instead of SELF !!
      }
    }
    
    class Derived extends Base {
      protected static $c = 'derived';
    }
    
    echo Base::getC();      // output "base"
    echo Derived::getC();   // output "derived"
    

提交回复
热议问题