In PHP, when the parent class calls the subclass method for breakfast, I can see a problem here. it is a bit interesting. it is generally not recommended for the parent class to call the subclass method, but the implementation methods are diversified, you can also understand.
Strong constraints in this case, otherwise it is easy to have bugs! In the inheritance relationship, the parent class does not know the Subclass. in this case, you must use an interface or abstract class to constrain it!
First look at the code
Say () ;}} class B extends A {protected function say () {echo 'B-say' ;}}$ B = new B (); $ B-> run (); // result: object (B) #1 (0) {} B-say
No. in the parent class, $ this already points to B.
I break down the inheritance. B actually becomes:
Say () ;}protected function say () {echo 'B-say' ;}}$ B = new B (); $ B-> run (); // result: object (B) #1 (0) {} B-say
Because B inherits the method of A, it seems that parent class A successfully calls the method of subclass B.
As mentioned in the question, when the say () method becomes private, the call fails. This is the function of the private range.
Let's take a look at the essence of run () inheritance.
In the decomposed code, Class B does have run (), but this run () belongs to its father A. It can only be used as "borrowed" and "property right" belongs to B, so when you call run (), you need to run it to father.
Note: When I ran to father A for use,The environment is..
But private said, what I modified,Can only be used in the current classAnd no one else can use it.
So an error is reported.
Inherit the called decomposition code:
Say (); // call the private method on the external new B object, failed} class B extends A {private function say () {echo 'B-say ';}} $ B = new B (); $ B-> run (); // Result: PHP Fatal error
If you want to have your own run method, you will need to rewrite it.
Say () ;}} class B extends A {public function run () {$ this-> say ();} private function say () {echo 'B-say' ;}}$ B = new B (); $ B-> run (); // Result: B-say
Click Generate QR code
In this article, Cheng Xiaobai
Creation, this article can be freely reproduced, cited, but must be signed by the author and indicate the source of the article.