Alex Rivera | Logout

Overriding static members in derived classes in PHP

Asked 2010-07-03T01:45:55.983
11
<?php
class Base {
  protected static $c = 'base';

  public static function getC() {
    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?

Edit
Report

1 Answer

0

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.

answered 2012-06-13T21:26:36.227

Your Answer