powerboy
powerboy

Reputation: 10961

Overriding static members in derived classes in PHP

<?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?

Upvotes: 11

Views: 6791

Answers (3)

Jan Thomas
Jan Thomas

Reputation: 131

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"

Upvotes: 4

Undolog
Undolog

Reputation: 562

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.

Upvotes: 0

deceze
deceze

Reputation: 522016

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.

Upvotes: 8

Related Questions