PHP in-depth understanding of object-oriented programming methods overloading and Method overlay (polymorphic), _php tutorial

Source: Internet
Author: User

PHP in-depth understanding of object-oriented programming methods overload and Method Overlay (polymorphic),

What is polymorphic?

Polymorphism (polymorphism) literally means "multiple states." In object-oriented languages, many different implementations of interfaces are polymorphic. The description of polymorphism is referenced by Charlie Calverts--polymorphism is a technique that allows you to set a parent object to be equal to one or more of his sub-objects, and after assignment, the parent can operate differently depending on the attributes of the child object currently assigned to it (excerpt from the "DELPHI4 Programming Technology Insider" )。 To put it simply, it is a word: Allow pointers of the subclass type to be assigned to the parent class type (yes, this is from Baidu Encyclopedia). So what is the role of polymorphism, and what is its actual development value? In the actual application development, the use of multi-state in object-oriented is mainly that the different sub-class objects can be treated as a parent class, and can block the differences between different sub-class objects, write out common code, and make general programming to adapt to the changing requirements.

Here are the two implementations of polymorphism in PHP

Method Overloading (overload)

Overloading is an implementation of the polymorphism of a class. function overloading means that an identifier is used as multiple function names, and the function can be distinguished by the number of arguments or parameter types of the function, and the call does not get confused. That is, when called, although the method has the same name, 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";  

If PHP directly supports method overloading. Then the above example will return different values when the arguments are passed and no arguments are passed. However, PHP does not directly support overloading, which means that if you define it directly as above, you will get an error. What's wrong with the report? will report the error as follows.

This means that a function cannot be defined repeatedly, and the number of errors is exactly the following line.

Therefore, PHP is not directly support overloading. It's so half a day that PHP doesn't support it. Don't worry, I said is not directly support, so we can let PHP indirectly support. This is the time to use a function to support overloading. is __call (). The __call () method must have two parameters. The first contains the called method name, and the second parameter contains the array of arguments passed to the method. This method allows you to implement functions that are 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]);    }  

When defining a method, you can see that there are three branches, and if an object is passed to the display () method, the Displayobject () method is called, and if an array is passed, call Displayarray (); The Displayscalar () method is called ... You can see the following call when the first one is passed an array, then call Displayarray (). The second passed in is not an object or an array, it belongs to something else, and the Displayscalar () method is called. So this way, a method overload similar to other languages is implemented using the __call () method.

Method override (Override)

The so-called coverage, in essence, is rewriting. That is, when a subclass inherits some of the methods of the parent class, and the subclass defines the same method within it, the newly defined method overrides the inherited method of the parent class, and the subclass can only invoke its internally defined methods.

There are several requirements:

1. When a parent class and subclass have a method that has exactly the same parameters and names, the subclass method overrides the method of the parent class.

2. The access modifier can be different when the method is overridden, but the access scope of the subclass must be greater than or equal to the access scope of the parent class.

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

Here is an explanation of these points:

1th, the parameters must be consistent before the method coverage can be achieved. When the number of arguments is inconsistent, an error is reported (this involves the method overload described above). When the method name is inconsistent, it is not overwritten, just the new method defined by the subclass. ;

2nd, this is the PHP language design rules. I understand that it is easier to access the high level of things, if you go to the bottom of the things to access the permissions must be higher.

Look at the code:

Class people{  protected function sing () {    echo "person sings";  }} class woman extends people{public  function sing () {    echo "woman sings";  

This is normal to output "woman singing". However, when the Sing () method in woman is changed to proctcted and the parent element is changed to public (), the following error is reported when the access permission of the parent class is set greater than the subclass.

3rd, the parameter and the name are required, specifically, the number of parameters required is the same as the parent class, not the parameter name. That is, the passed parameter name can be any, as long as the number of guaranteed delivery is the same.

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

PS: The difference analysis of several concepts of rewriting, overwriting, overloading and polymorphism

override-> override (= overwrite), overload-> overloaded, polymorphism-and polymorphic

Override is a way to override (overwrite) a method to implement different functions. It is generally used to override (re-implement) a method in the parent class when the subclass inherits the parent class.
Override (Overwrite) the rule:

1. The parameter list of the overridden method must be exactly the same as the overridden method, otherwise it cannot be called overridden instead of overloaded.
2. The access modifier for the overridden method must be greater than the access modifier (public>protected>default>private) of the overridden method.
3. The return value of the overridden method must be consistent with the return of the overridden method;
4. The overridden method throws an exception that must be the same as the exception thrown by the overridden method, or its subclass;
5. The overridden method cannot be private, otherwise only a new method is defined in its subclass and is not overridden.
6. Static methods cannot be overridden as non-static methods (compile error).

Overload are overloads that are typically used to implement several overloads within a class that have the same names and different parameter forms.

Rules for overloading:

1, in the use of overloading can only be achieved by the same method name, different parameter form. Different parameter types can be different parameter types, different parameter numbers, different parameter order (parameter types must not be the same);
2, can not be overloaded by access rights, return type, thrown exception;
3, the method of the exception type and number will not affect the overload;

The concept of polymorphism is more complex and has multiple meanings, and an interesting but not rigorous argument is that inheritance is a method of using the parent class of a subclass, and polymorphism is the method by which the parent class uses subclasses.

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

As an 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 ());//Inherit   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) {//reload  return 4;  }} Class Triangle extends Shape {public  int getsides () {///override to implement Polymorphic   return 3;}  } Class Rectangle extends Shape {public  int getsides (int i) {//overload  return i;  }}

Note that the method of the Triangle class is overridden, whereas the method of the rectangle class is overloaded. Comparing the two, you can find the advantages of polymorphism to overloading:

In the case of overloading, each subclass in the parent class is overloaded with a method that obtains the number of edges;

If polymorphism is used, the parent class provides only the interface that obtains the number of edges, and the number of sides to which the shape is obtained, which is implemented (rewritten) in the subclass.

Articles you may be interested in:

    • PHP Object-oriented final class and final method
    • Introduction to Overloading (overload) and overwrite (override) in PHP and Java
    • PHP Object-oriented three-character learning (full understanding of abstraction, encapsulation, inheritance, polymorphism)
    • Object-oriented error handling methods such as exception handling, error throwing and callback functions for PHP
    • Object-oriented programming of PHP learning notes
    • An analysis of PHP object-oriented public private protected access modifier
    • PHP Object-oriented tour: in-depth understanding of static variables and methods
    • PHP Object-oriented programming (OOP) learning notes (i)-abstract classes, object interfaces, instanceof, and contract programming
    • Calls to static and static methods in object-oriented PHP
    • Application of method overloading (overwriting) in PHP inheritance true techarticle PHP in-depth understanding of object-oriented programming methods overloading and method coverage (polymorphic), what is polymorphic? Polymorphism (polymorphism) literally means "multiple states." In object-oriented ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.