Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize polymorphic method overloading and method coverage in PHP

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to achieve polymorphic method overloading and method coverage in PHP". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is polymorphism?

Polymorphism literally means "multiple states". In object-oriented languages, many different implementations of interfaces are polymorphisms. Citing Charlie Calverts's description of polymorphism-polymorphism is a technique that allows you to set a parent object to be equal to one or more of its children. After assignment, the parent object can operate differently according to the characteristics of the child object currently assigned to it (excerpt from the inside of Delphi4 programming techniques). To put it simply, it is a sentence: allow pointers of subclass types to be assigned to pointers of parent types (yes, this paragraph comes from Baidu encyclopedia). So what is the role of polymorphism, and what is the actual development value of it? In practical application development, the use of polymorphism in object-oriented mainly lies in that different subclass objects can be treated as a parent class, and the differences between different subclass objects can be shielded and universal code can be written. make general programming to adapt to changing requirements.

Here are two implementations of polymorphism in PHP

Method overload (overload)

Overloading is an implementation of the polymorphism of a class. Function overloading means that an identifier is used as multiple function names, and these functions with the same name can be distinguished by the number or type of parameters of the function, and the call does not cause confusion. That is, when the method is called, although the method name is the same, the corresponding function can be called automatically according to the different parameters.

Class A {public function test () {echo "test1";} public function test ($a) {echo "test2";}} $a=new A (); $a-> test (); $a-> test ($a)

If php directly supports method overloading. Then the above example will return different values after passing parameters and not passing parameters. However, php does not directly support overloading, which means that if you directly follow the above definition, you will report an error. What would be wrong? The following error will be reported.

This means that the A function cannot be defined repeatedly, and the number of rows reported as errors is exactly the following line.

Public function test ($a) {

So php does not directly support overloading. After saying that for a long time, php does not support it. Don't worry, what I'm saying is that we don't support it directly, so we can let php support it indirectly. At this point, a function is used to support overloading. This is _ _ call (). The _ _ call () method must take two parameters. The first contains the name of the method being called, while the second parameter contains the array of parameters passed to the method. You can use this method to implement functions similar to function overloading. Look at the code below.

Public function _ _ call ($method,$p) {if ($method== "display") {if (is_object ($p [0])) {$this- > displayObject ($p [0]);} else if (is_array ($p [0])) {$this- > displayArray ($p [0]);} else {$this- > displayScalar ($p [0]);}} / below is the call $ov=new overload;$ov- > display defined above $ov- > display ('cat')

When defining a method, you can see that there are three branches: if an object is passed to the display () method, the displayObject () method is called; if an array is passed, displayArray () is called; if something else is passed, the displayScalar () method is called. You can see that when the following call is made, the first one is passed an array, then displayArray () is called. The second is neither an object nor an array, it belongs to something else, and the displayScalar () method is called. So this implements method overloading similar to other languages with the _ _ call () method.

Method override (override)

The so-called coverage is essentially rewriting. That is, when the subclass inherits some of the methods of the parent class, and the subclass defines the same method within it, the newly defined method will override the inherited parent method, and the subclass can only call its internally defined methods.

There are the following requirements:

1. When a parent class and a child class have a method with exactly the same parameter and name, the subclass method overrides the parent class method.

two。 When implementing method overrides, the access modifier can be different, but the access scope of the subclass must be greater than or equal to that of the parent class.

3. Requires the same parameters as the name. The subclass is not required, the parent class has the same name.

Here is an explanation of these points:

First, the parameters must be consistent to achieve method overrides. When the number of parameters is inconsistent, an error will be reported (this involves overloading the method mentioned above). When the method name is inconsistent, it will not be overwritten, just the method newly defined by the subclass.

Second, this is the design rule of languages such as php. What I understand is that it is easier to access something on a higher level, and it will certainly have higher permissions if you go to the bottom layer.

Look at the code:

Class people {protected function sing () {echo "people sing";}} class woman extends people {public function sing () {echo "Women sing";}} $woman1=new woman (); $woman1- > sing ()

This is a normal way to output "women singing". However, when the sing () method in woman is changed to proctcted and the parent element is changed to public (), the following error will be reported when the access permission of the parent class is greater than that of the subclass.

The third point is to require the parameter to be the same as the name, specifically that the number of parameters is the same as the parent class, not the parameter name. That is, the name of the passed parameter can be any, as long as the number of passed is the same.

The above briefly introduces two implementations of polymorphism in the PHP language.

PS: an Analysis of the differences between the Concepts of rewriting, overwriting, overloading and Polymorphism

Override- > overwrite (= overwrite), overload- > overload, polymorphism-> polymorphism

Override is rewritten (overridden) by a method to achieve different functions. It is generally used for subclasses to override (reimplement) methods in the parent class when inheriting from the parent class.

Rules for rewriting (overwriting):

1. The parameter list of the overridden method must be exactly the same as that of the overridden method, otherwise it cannot be called rewriting but overloading.

2. The access modifier of the overridden method must be greater than that of the overridden method (public > protected > default > private).

3. The return value of the overridden method must be the same as that of the overridden method

4. The exception thrown by the overridden method must be consistent with the exception thrown by the overridden method, or its subclass

5. The overridden method cannot be private, otherwise a new method is defined in its subclass, and it is not rewritten.

6. Static methods cannot be rewritten as non-static methods (there will be compilation errors).

Overload is overloaded and is typically used to implement several overloaded methods within a class with the same name but different parameter forms.

Rules for overloading:

1. When using overloading, it can only be realized by the same method name and different parameter forms. Different parameter types can be different parameter types, different number of parameters, different parameter order (parameter types must be different)

2. Cannot be overloaded by access permission, return type, and thrown exception

3. The exception type and number of methods will not affect the overloading.

The concept of polymorphism is complex and has many meanings. An interesting but not rigorous statement is that inheritance is a method in which a subclass uses a parent class, while polymorphism is a method in which a parent class uses a subclass.

In general, we use polymorphism to avoid code bloated and difficult to maintain due to heavy overloading in the parent class.

For example:

Public class Shape {public static void main (String [] args) {Triangle tri = new Triangle (); System.out.println ("Triangle is a type of shape?" + tri.isShape ()); / / inheritance Shape shape = new Triangle (); System.out.println ("My shape has" + shape.getSides () + "sides."); / / polymorphic Rectangle Rec = new Rectangle (); Shape shape2 = Rec System.out.println ("My shape has" + shape2.getSides (Rec) + "sides."); / / overload} public boolean isShape () {return true;} public int getSides () {return 0;} public int getSides (Triangle tri) {/ / overload return 3;} public int getSides (Rectangle rec) {/ / overload return 4;}} class Triangle extends Shape {public int getSides () {/ / rewrite to implement polymorphic return 3 }} class Rectangle extends Shape {public int getSides (int I) {/ / reload return I;}}

Note that the method of the Triangle class is overridden, while the method of the Rectangle class is overloaded. By comparing the two, we can find the advantages of polymorphism over overloading:

If you use overloading, overload a method that gets the number of edges for each subclass in the parent class

If polymorphism is used, the parent class only provides the interface to get the number of edges, and how to get the number of edges of which shape is implemented (overridden) in the subclass.

This is the end of the content of "how to achieve polymorphic method overloading and method override in PHP". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report