1. What is polymorphism? Polymorphism literally means "multiple 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 between different subclass objects can be shielded and universal code and make general programming to adapt to changing needs.
/**
* Shape Interface
*
* @version 1.0
* @copyright
* (1) Using interface (interface), you can specify which methods a class must implement, but you do not need to define the specific content 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. This 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());
?>
The above has introduced PHP polymorphism, including PHP content. I hope it will be helpful to friends who are interested in PHP tutorials.