For php inherited application scenarios with method overload (overwrite), php overload. The application of method overload (overwrite) in php Inheritance. the example in this article analyzes the application of method overload (overwrite) in php inheritance. Share it with you for your reference. Analyze the application scenarios of method overload (overwrite) in php inheritance, and php overload
This article analyzes the application scenarios of method overload (overwrite) in php inheritance. Share it with you for your reference. The specific analysis is as follows:
Override/override-when to use: when the parent class knows that all subclasses require a method, but the parent class does not know how to write this method, method overloading is required. At this time, the subclass can be rewritten to overwrite this method.
Common examples: the parent class (animals) knows that its sub-classes (cats and dogs) are called, but they are called differently. Therefore, the parent class cannot write this method, only child classes (cats and dogs) can be defined. The code is as follows:
<? Phpclass Animal {public $ name; protected $ price; function cry () {echo "I don't know how animals are called" ;}} class Dog extends Animal {function cry () {echo "Wang... ";}} class Pig extends Animal {function cry () {echo" hum... "}}?>
Key points and details of method overload/overwrite (a bit confusing to read ):
1. a subclass method is required. its method name and parameter list are exactly the same as the parent class method. For example, in cry (), you cannot add a parameter or change it to cry ($ naaa. Note: the same parameter name is not required, but the number of parameters is the same.
2. the so-called overload or overwrite does not overwrite the method of the parent class. It can also be understood that if the subclass does not find this method in its own class when calling this method, it will find the parent class to see if there is any such method. This is also an understanding of polymorphism.
3. if a method in a subclass inherits the content of methods with the same name in the parent class, you can use parent: method name or parent class name: method name to inherit. Used in the method defined by the subclass.
4. access permission. the access range of the subclass is> = the access range of the parent class. that is, if the parent class is protected function cry (), the subclass can only be protected or public.
I hope this article will help you with php programming.
In this article, we have analyzed the application scenarios of method overload (overwriting) in php inheritance. Share it with you for your reference. Specific analysis...