For some reason, PHP class constants don't play nicely with inheritance.
For example, suppose you have the following code:
class Foo {
const VAR = 'foo';
public function __construct() {
echo self::VAR;
}
}
class Bar extends Foo {
const VAR = 'bar';
}
// This will actually print out 'foo' even though we would expect it to print out 'bar'
$bar = new Bar();
You can see here that there is a class Foo that has a constant variable named VAR
, and the constructor function for that class (that executes when a new object of that type is created), says to print out the value of that variable.
We then have a second class Bar that extends class Foo. With this type of inheritance, child class Bar is meant to inherit all properties and methods from its parent class Foo. The problem, unfortunately, is that this doesn't extend to constants. The solution to this problem is to use ReflectionObjects. The code below demonstrates the proper way to retrieve a class constant that obeys inheritance.