Home >Backend Development >PHP Tutorial >PHP polymorphism, php polymorphism_PHP tutorial

PHP polymorphism, php polymorphism_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:54:42847browse

PHP polymorphism, php polymorphism

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());


?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1119060.htmlTechArticlePHP polymorphism, php polymorphism 1. What is polymorphism? Polymorphism (Polymorphism) literally means Various shapes. It can be understood as multiple forms of expression, that is, an external interface, multiple internal...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn