2

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?

amigne
  • 53
  • 5
  • 1
    Have you tried using `static::CST` instead of `self::CST`? – Dharman Apr 21 '19 at 11:04
  • No. I was not aware of this way to refer to a static constant or property... I just successfully tested it. Thanks a lot for the help. – amigne Apr 21 '19 at 11:13

1 Answers1

2

Dharman suggested to use static::CST instead of self::CST.

This was the solution to my problem.

amigne
  • 53
  • 5
  • Now that I know the existence of "static::" form, I found very interesting information about the difference between "self::" and "static::": https://stackoverflow.com/questions/11710099/what-is-the-difference-between-selfbar-and-staticbar-in-php – amigne Apr 21 '19 at 11:19