Do child classes inherit parent constants and if so how do I access them?
✔ Recommended Answer
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 1echo MyChildClass::CONSTANT_1; // outputs 2
Source: stackoverflow.com
Answered By: Chris Leyva
Yes, child classes do inherit constants from their parent classes in PHP.
To access a constant defined in the parent class, you can use the parent::
keyword followed by the constant name. Here's an example:
phpclass ParentClass {
const PARENT_CONST = 'Parent Constant Value';
}
class ChildClass extends ParentClass {
}
echo ParentClass::PARENT_CONST . "\n"; // Outputs "Parent Constant Value"
echo ChildClass::PARENT_CONST . "\n"; // Outputs "Parent Constant Value"
In this example, we define a ParentClass
with a constant PARENT_CONST
. We then define a ChildClass
that extends the ParentClass
. The ChildClass
inherits the PARENT_CONST
constant from the ParentClass
.
We can access the PARENT_CONST
constant in both the ParentClass
and ChildClass
using the ::
operator. When accessing the constant in the ChildClass
, we use the parent::
keyword followed by the constant name to refer to the parent class constant.
Note that constants are always accessed statically, even if you are accessing them from an object context.
Comments
Post a Comment