PHP polymorphism and php Polymorphism
1. What is polymorphism?
Polymorphism literally means "multiple shapes ". It can be understood as a variety of forms, that is, "one external interface, multiple internal implementation methods ". In the object-oriented theory, polymorphism is generally defined as: the same operation acts on instances of different classes and will produce different execution results. That is, different classes of objects receive different results when they receive the same message.
In actual application development, the polymorphism in object orientation is mainly used to treat different subclass objects as a parent class, and the differences between different subclass objects can be shielded, write Common Code and make general programming to adapt to the changing needs.
<? Php
/**
* Shape Interface
*
* @ Version 1.0
* @ Copyright
* (1) using interfaces, you can specify the methods that a class must implement, but you do not need to define the specific content of these methods.
* (2) We can use interfaces to define an interface, just like defining a standard class, but defining all methods is empty.
* (3) all methods defined in the interface must be public, which is a feature of the interface.
*/
Interface Shape {
Public function draw ();
}
/**
* Triangle
*
* @ Uses Shape
* @ Version 1.0
* @ Copyright
* (1) You can use the implements operator to implement an interface. Class must implement all methods defined in the interface, otherwise a fatal error will be reported.
* (2) 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 ());
?>