Do child classes inherit parent constants and if so how do I access them?
class, oop, php
Solution
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;
In both parent and children classes, you can use:
static::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
Problem
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 { // I want to access CONSTANT_1 } ```