Overriding class constants and properties

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?

+63
override inheritance oop php constants
Nov 28 '12 at 20:12
source share
2 answers

self:: Does not apply to inheritance and always refers to the class in which it is executed. If you are using php5.3 +, you can try static::TEST since static:: is an inheritance.

The difference is that static:: uses "late static binding". More detailed information can be found here:

http://php.net/manual/en/language.oop5.late-static-bindings.php

Here is a simple test script I wrote:

 <?php class One { const TEST = "test1"; function test() { echo static::TEST; } } class Two extends One { const TEST = "test2"; } $c = new Two(); $c->test(); 

Exit

 test2 
+118
Nov 28 '12 at 20:22
source share

In PHP, self refers to the class in which the called method or property is defined. Therefore, in your case, you call self in ChildClass , so it uses a variable from this class. Then you use self in the ParentClass , so it will refer to the variable in this class.

if you still want the child class to override the const parent class, then set up the following code in the parent class:

 public function showTest(){ echo static::TEST; echo $this->test; } 

Pay attention to the static . This uses late static binding. Now you parent class will call const of your child class.

+10
Nov 28 '12 at 20:19
source share



All Articles