I would like to better understand why in the scenario below there is a difference in how class constants and instance variables are inherited.
<?php class ParentClass { const TEST = "ONE"; protected $test = "ONE"; public function showTest(){ echo self::TEST; echo $this->test; } } class ChildClass extends ParentClass { const TEST = "TWO"; protected $test = "TWO"; public function myTest(){ echo self::TEST; echo $this->test; } } $child = new ChildClass(); $child->myTest(); $child->showTest();
Output:
TWO TWO ONE TWO
In the above code, ChildClass does not have a showTest () method, so the ParentClass showTest () inheritance method is used by inheritance. The results show that since the method runs in ParentClass, the version of the TEST constant in ParentClass is evaluated, whereas because it is evaluated in the context of ChildClass through inheritance, the member variable $ TestClassClass is evaluated.
I read the documentation, but I donβt seem to see a mention of this nuance. Can anyone shed some light on me?
override inheritance oop php constants
Tom Auger Nov 28 '12 at 20:12 2012-11-28 20:12
source share