Home > Article > Backend Development > PHP polymorphism, php polymorphism_PHP tutorial
1. What is polymorphism
Polymorphism is understood literally That’s “many shapes.” It can be understood as multiple forms of expression, that is, "one external interface and multiple internal implementation methods." In object-oriented theory, the general definition of polymorphism is: the same operation will produce different execution results when applied to instances of different classes. That is, when objects of different types receive the same message, they will get different results.
In actual application development, the main reason for using object-oriented polymorphism is that different subclass objects can be treated as one parent class, and the differences that exist between different subclass objects can be shielded. Differences, write common code, and make common programming to adapt to changing needs.
/**
* Shape Interface
*
* @version 1.0
* @copyright
* (1) Using interface, you can specify which methods a class must implement, but it is not required Define the specifics of these methods.
* (2) We can define an interface through interface, just like defining a standard class, but all the methods defined in it are empty.
* (3) All methods defined in the interface must be public, which is a characteristic of the interface
*/
interface Shape {
public function draw();
}
/**
* Triangle
*
* @uses Shape
* @version 1.0
* @copyright
* (1) To implement an interface, you can use the implements operator. The class must implement all methods defined in the interface, otherwise a fatal error will be reported.
* (2) If you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces.
*/
class Triangle implements Shape {
public function draw() {
print "Triangle::draw()n";
}
}
/ **
* Rectangle
*
* @uses Shape
* @version 1.0
* @copyright
*/
class Rectangle implements Shape {
public function draw() {
print "Rectangle::draw()n";
}
}
/**
* Test Polymorphism
*
* @version 1.0
* @copyright
*/
class TestPoly {
public function drawNow($shape) {
$shape->draw();
}
}
$test = new TestPoly();
$test->drawNow(new Triangle());
$test->drawNow(new Rectangle());
?>