I'm wanting to create an class inheriting (extending) another PHP class with a protected const that I want to override in my extending class.
I created a parent class (A for the example) and an inheriting class (B for the example). class A
has a protected const
(named CST) defined. class B
overrides this const as well.
When calling a method class B inherited from A that displays self::CST
, the printed value is the CST value from A, not the const CST overrided in B.
I observe the same behavior with a static property named $var
.
It seems that self
used in methods is always refering to the defining class (A in my example) and not the class used for calling the static method.
class A
{
protected static $var = 1;
protected const CST = 1;
public static function printVar()
{
print self::$var . "\n";
}
public static function printCST()
{
print self::CST . "\n";
}
}
class B extends A
{
protected static $var = 2;
protected const CST =2;
}
A::printVar();
A::printCST();
B::printVar();
B::printCST();
Is there a way to permit my static method printCST()
to display 2 when called with B::printCST()
without rewriting the method in class B
and to benefit code reusability of OOP?