Home > Article > Backend Development > Application occasions of method overloading (overwriting) in php inheritance, php overloading_PHP tutorial
This article analyzes the application scenarios of method overloading (overwriting) in PHP inheritance. Share it with everyone for your reference. The specific analysis is as follows:
Method override/override - under what circumstances is it used: When the parent class knows that all subclasses need to use a method, but the parent class does not know how to write this method, it needs to be used Method overloading. At this time, you can let the subclass override this method.
Popular example - the parent class (animal) knows that its subclasses (cats and dogs) can bark, but their barks are different, so the parent class cannot write this method and can only let the subclasses (cats) and dogs) to define. The code is as follows:
<?php class Animal{ public $name; protected $price; function cry(){ echo "不知道动物怎么叫"; } } class Dog extends Animal{ function cry(){ echo "汪汪..."; } } class Pig extends Animal{ function cry(){ echo "哼哼..." } } ?>
Key points and details of method overloading/overriding (reading a bit awkward):
1. The method name and parameter list of the subclass method are required to be exactly the same as the parent class method. For example, cry() in the example cannot add parameters, so change it to cry($naaa), etc. Note: The parameter names are not required to be the same here, but the number of parameters is required to be the same.
2. The so-called overloading or overwriting does not mean overwriting the method of the parent class. It can also be understood this way: if a subclass calls this method and cannot find this method in its own class, then it will go to the parent class to see if there is such a method. This is also the understanding of polymorphism
3. If a method in the subclass wants to inherit the content of the method with the same name in the parent class, you can use parent::method name or parent class name::method name to inherit. Used within methods defined by subclasses.
4. Access permission issues, the access scope of the subclass >= the access scope of the parent class, that is, if the parent class is a protected function cry(), the subclass can only be protected or public.
I hope this article will be helpful to everyone’s PHP programming design.