<?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?
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.
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.
In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With