Home >Backend Development >PHP Tutorial >PHP object-oriented guide (15) Polymorphic application_PHP tutorial
Application of polymorphism
Polymorphism is another one of the three major features of object-oriented besides encapsulation and inheritance. In my personal opinion, although polymorphism can be achieved in PHP, it is different from C++ and Java. Compared with these object-oriented languages, polymorphism is not so prominent, because PHP
itself is a weakly typed language. There is no conversion of parent class objects into subclass objects or subclass objects into parent class objects.
object problem, so the application of polymorphism is not so obvious; the so-called polymorphism refers to the ability of a program to handle multiple types of
objects. For example, when working in a company, the financial department pays wages every month , the same salary payment method, different employees or employees in different positions within the company are all paid through this method, but the wages paid are different.
So the same method of paying wages appears in many forms. For object-oriented programs, polymorphism is to assign the subclass object
to the parent class reference, and then call the method of the parent class to execute the method of the subclass overriding the parent class, but in PHP it is
Weakly typed, object references are the same regardless of parent class reference or subclass reference.
Let’s look at an example now. First of all, to use polymorphism, there must be a relationship between parent class objects and subclass objects. Make a
shape interface or abstract class as the parent class. There are two abstract methods in it, one is to find the perimeter, and the other is to find the
area; there are many subclasses of this interface Different shapes, each shape has a perimeter and an area, and because the parent class is an interface, the subclass must implement the two abstract methods of the parent class's perimeter and area, so The purpose
is that each subclass of different shapes must comply with the specifications of the parent class interface and have methods for calculating perimeter and area.
Code snippet
Copy code