开发者

Overriding static members in derived classes in PHP

<?php
class Base {
  protected static $c = 'base';

  public static function g开发者_开发问答etC() {
    return self::$c;
  }
}

class Derived extends Base {
  protected static $c = 'derived';
}

echo Base::getC(); // output "base"
echo Derived::getC();    // output "base", but I need "derived" here!
?>

So what's the best workaround?


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.


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"


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜