Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
powerboy Avatar asked Jul 03 '10 01:07

powerboy


People also ask

Can you override static methods in PHP?

Here comes the call of static method with static keyword. In case there is no overridden function then it will call the function within the class as self keyword does. If the function is overridden then the static keyword will call the overridden function in the derived class.

Are static methods members inherited to derive class?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

Can we inherit static class in PHP?

In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.

Can the subclass inherit static members?

Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared. Constructors, static initializers, and instance initializers are not members and therefore are not inherited.


2 Answers

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.

like image 107
deceze Avatar answered Nov 15 '22 14:11

deceze


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"
like image 36
Jan Thomas Avatar answered Nov 15 '22 13:11

Jan Thomas