Overriding static members in derived classes in PHP

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


        
相关标签:
3条回答
  • 2021-01-11 18:04

    The best way to solve this is to upgrade to PHP 5.3, where late static bindings are available. If that's not an option, you'll unfortunately have to redesign your class.

    0 讨论(0)
  • 2021-01-11 18:05

    You have to re-implment base class method; try with:

    class Derived extends Base {
      protected static $c = 'derived';
    
      public static function getC() {
        return self::$c;
      }
    }
    

    As you see, this solution is very useless, because force to re-write all subclassed methods.

    The value of self::$c depends only on the class where the method was actually implemented, not the class from which it was called.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题