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: