Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do child classes inherit parent constants and if so how do I access them?

Tags:

Questions says it all really.

I have constants defined in my parent class. I have tried $this->CONSTANT_1 but it's not working.

class MyParentClass{      const CONSTANT_1=1 }  class MyChildClass extends MyParentClass{   //want to access CONSTANT_1    } 
like image 585
Claire Avatar asked Jan 10 '14 13:01

Claire


1 Answers

I think you would need to access it like this:

self::CONSTANT_1; 

or alternatively "parent", which will always be the value established in the parent class (i.e., the constant's immutability is maintained):

parent::CONSTANT_1; 

Interesting

One thing that is interesting to note is that you can actually override the const value in your child class.

class MyParentClass{      const CONSTANT_1=1; }  class MyChildClass extends MyParentClass{      const CONSTANT_1=2; }  echo MyParentClass::CONSTANT_1; // outputs 1 echo MyChildClass::CONSTANT_1; // outputs 2 
like image 82
Chris Leyva Avatar answered Sep 28 '22 09:09

Chris Leyva