in PHP, I often write a class, the class writes a common method, and then let the subclass to inherit to get the corresponding function. Let's say there's a parent class roughly:
<?phpclass father{public function construct () { echo ' I am the constructor of the parent class! '; } protected function Say ($str = ' Hello world! ') { echo ' said a word: '. $str; }}? >
Then, make a subclass to inherit him:
<?phpclass Chirld extends father{public construct () { echo ' I am a subclass of construction method ~ '; }}
At this point you instantiate the subclass, and the result will be 我是子类的构造方法~
!
Of course, because of the 继承
relationship, the subclass is a method that can call the parent class say()
.
If you want to implement the constructor of the parent class, but you want to implement the subclass constructor, you can do it this way:
<?phpclass Chirld extends father{public construct () { parent::construct (); Echo ' I am a subclass of construction method ~ '; }? >
This will output 我是父类的构造方法!
and 我是子类的构造方法~
.
Suppose you define such a method in a subclass:
protected function Say ($str = ") { echo ' I am a subclass of say ';}
Then, the method you inherited from the parent class sys()
will be rewritten, so the result of the call is: 我是子类的say
.
What happens if you define that?
Public function say ($str = ') { echo ' I am a subclass of method Oh ~ ';}
This kind of writing is still possible. PHP differs from other strongly typed languages in that the PHP rewrite method allows you to "go public" with the overridden method, without allowing you to "privatize down", as you would say in the case where you private
would definitely have an error, whereas a language like C + + would be the opposite.
PHP's idea of this situation is that your father gave you a protected level of inheritance, at this point in your hand is the protection level, your father allows you to share with others, that is public
, but do not allow you to hide, that is, you have to swallow private
certainly not.
At this point you are sure to ask, so say()
what happens to the parent class private
?
The result is that the parent class has been privatized and the subclass cannot inherit at all, so your method in the subclass say()
will be as much as you can.
Another problem is that the parent class has defined the sys()
optional parameters in the band, so what if you have no parameter definitions in the subclass like this?
Public function Say () { echo ' haha. I have no parameters, yes ~ ';}
The
result can still work, except for a e_strict
level prompt. The reason is that the PHP standard is that the number of parameters must be aligned with the parent class, and of course the error level can be set in php.ini.