PHP object-oriented -- polymorphism-PHP source code

Source: Internet
Author: User
Polymorphism refers to the ability to redefine or change the nature and behavior of a class based on the context of the class. Polymorphism refers to the ability to redefine or change the nature and behavior of a class based on the context of the class.

PHP does not support implementing polymorphism through overload, but PHP can achieve polymorphism through redirection. As follows:

Class a {function test ($ I) {// $ I can be any type of variable print_r $ I ;}}

As shown in the preceding example, because PHP is a weak type language, $ I can be a variable of any type, such a function can realize the polymorphism of the parameter type overload method in a strong type language such as java.

This method is more convenient and efficient than JAVA parameter type overload, but there are also problems, as follows:

 Draw () ;}} class Polygon {function draw () {echo "draw a polygon" ;}} class Circle {function draw () {echo "draw a circle" ;}}?>

It can be seen that such flexible polymorphism requires some control. after PHP5.3, you can set type restrictions on parameters as follows:

// Java-like, add a restriction class name function drawPolygon (Polygon $ polygon) {$ polygon-> draw ();} before the variable parameter ();}

In this way, only Polygon and its subclass can be passed in.

Another method is to change the number of parameters. PHP also does not support Method overloading, so some workarounds are also required, as shown below:

 

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.