Deep understanding of PHP object-oriented programming method overloading and method coverage (polymorphism), _ PHP Tutorial

Source: Internet
Author: User
Tags php exception handling
PHP object-oriented programming: deep understanding of Method overloading and method coverage (polymorphism ),. PHP object-oriented programming: deep understanding of Method overloading and method coverage (polymorphism). What is polymorphism? Polymorphism literally means "multiple states ". In-depth understanding of object-oriented PHP object-oriented programming method overloading and method coverage (polymorphism ),

What is polymorphism?

Polymorphism literally means "multiple states ". In Object-Oriented Language, multiple implementation methods of interfaces are polymorphism. Reference Charlie Calverts's description of polymorphism-polymorphism is a technology that allows you to set a parent object to be equal to one or more of its sub-objects, the parent object can operate in different ways based on the features assigned to its sub-objects (from "Delphi4 programming technology insider "). To put it simply, you can assign a pointer of the subclass type to the pointer of the parent class (that is, Baidu Encyclopedia ). So what is the role of polymorphism and what is its actual development value? In actual application development, the polymorphism in object orientation is mainly used to treat different subclass objects as a parent class, and the differences between different subclass objects can be shielded, write common code and make general programming to adapt to the changing needs.

Below are two implementations of polymorphism in PHP.

Method overload)

Overload is an implementation of class polymorphism. Function overload means that an identifier is used as multiple function names and can be used to distinguish these functions with the same name by the number or type of function parameters. the call is not obfuscated. That is, although the method name is the same during the call, the corresponding function can be automatically called according to 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. After the preceding example is executed, different values are returned if the parameter is passed or the parameter is not passed. However, php does not directly support overloading, which means that if you define it as above, an error will be reported. What error will be reported? The following error is reported.

This means that function A cannot be repeatedly defined, and the number of rows that report an error is exactly the following line.

public function test($a){ 

Therefore, php does not directly support overloading. Php does not support it for so long .. Don't worry. I am not talking about direct support, so we can make php support indirectly. At this time, we need to use a function to support overloading. It is _ call (). The _ call () method must have two parameters. The first contains the name of the called method, and the second parameter contains an array of parameters passed to the method. You can use this method to implement functions similar to function overloading. See the following code.

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]) ;}} // The following is the call to the above definition $ ov = new overload; $ ov-> display (array (1, 2, 3); $ 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, call displayArray (); if other content is passed, the displayScalar () method is called... We can see that when the following call is performed, the first is to pass an array, and displayArray () is called (). If the second input is not an object or an array, it belongs to other content and the displayScalar () method is called. Therefore, the _ call () method is used to implement method overloading similar to other languages.

Override)

The so-called overwrite is essentially a rewrite. That is, when the subclass inherits some methods of the parent class, and the subclass defines the same method internally, the newly defined method will overwrite the inherited methods of the parent class, subclass can only call its internally defined methods.

There are the following requirements:

1. when a parent class and a subclass have a method with the same parameters and names, the subclass method will overwrite the method of the parent class.

2. when method override is implemented, the access modifier can be different, but the access range of the subclass must be greater than or equal to the access range of the parent class.

3. the parameters and names must be the same. The parent class name is the same.

The following are some explanations:

The first point must have the same parameters to implement method override. If the number of parameters is different, an error is returned (this involves the method overload mentioned above ). If the method names are inconsistent, the method will not be overwritten, but the new method defined by the Subclass .;

Second, this is the design rules for php. What I understand is that it is easier to access things on the higher layer. if you access things on the lower layer, the permissions must be higher.

Check the code:

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

In this way, "Singing for women" can be output normally ". 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 set to be greater than that of the child class.

Third, the parameter must be the same as the name. Specifically, the number of parameters must be the same as that of the parent class, rather than the same parameter name. That is, the name of the passed parameter can be any, as long as the number of passed parameters is the same.

The above briefly introduces two implementations of polymorphism in PHP.

PS: analysis of the differences between rewriting, overwriting, overloading, and polymorphism

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

Override overwrites a method to implement different functions. It is generally used to override (re-implement) the methods in the parent class when the subclass inherits the parent class.
Rewrite (overwrite) rules:

1. the parameter list of the override method must be exactly the same as that of the method to be overwritten. Otherwise, it cannot be called a rewrite but a heavy load.
2. the access modifier of the override method must be greater than the access modifier (public> protected> default> private) of the override method ).
3. the returned value of the method to be rewritten must be the same as that of the method to be rewritten;
4. The Exception thrown by the override method must be the same as the exception thrown by the override method, or its subclass;
5. the method to be overwritten cannot be private. Otherwise, a new method is defined in its subclass and is not overwritten.
6. static methods cannot be rewritten as non-static methods (compilation errors may occur ).

Overload is an overloaded method. it is generally used to implement several Overloaded methods in a class. these methods have the same name and different parameter formats.

Reload rules:

1. you can only use the same method name and different parameter forms when using overload. Different parameter types can be different parameter types, different parameter numbers, and different parameter order (the parameter types must be different );
2. it cannot be overloaded by access permission, return type, or thrown exception;
3. the method exception type and quantity do not affect the heavy load;

The concept of polymorphism is complex and has multiple meanings of polymorphism. an interesting but not rigorous statement is that inheritance is the method that subclasses use the parent class, polymorphism means that the parent class uses the subclass method.

In general, polymorphism is used to avoid code bloated and difficult to maintain due to heavy loads 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 (); // inherits Shape shape = new Triangle (); System. out. println ("My shape has" + shape. getSides () + "sides. "); // polymorphism 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, implement polymorphism return 3 ;}} class Rectangle extends Shape {public int getSides (int I) {// overload return I ;}}

Note that the Triangle class method is overwritten, while the Rectangle class method is overloaded. By comparing the two, we can find out the advantages of polymorphism in Heavy load:

If overload is used, a method to obtain the number of edges must be reloaded for each subclass in the parent class;

If polymorphism is used, the parent class only provides the interface for obtaining the number of edges. as to the number of edges in the shape to be obtained, how to obtain the edges is implemented (rewritten) in the subclass ).

Articles you may be interested in:
  • PHP object-oriented final class and final method
  • Overload and override in PHP and JAVA
  • PHP Object-Oriented Learning (full understanding of abstraction, encapsulation, inheritance, and polymorphism)
  • PHP exception handling, error throws, callback functions, and other object-oriented error handling methods
  • Php learning notes-Object-oriented programming
  • Analysis on php object-oriented public private protected access modifier
  • PHP object-oriented journey: a deep understanding of static variables and methods
  • PHP object-oriented programming (oop) learning Notes (1)-abstract classes, object interfaces, instanceof and contractual programming
  • Php object-oriented call of static attributes and static methods
  • Application scenarios of method overload (overwrite) in php inheritance

What is polymorphism? Polymorphism literally means "multiple states ". In the object-oriented...

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: info-contact@alibabacloud.com 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.