PHP 多态,php多态_PHP教程

WBOY
Release: 2016-07-12 08:54:42
Original
778 people have browsed it

PHP 多态,php多态

1.什么是多态

多 态(Polymorphism)按字面上意思理解就是“多种形状”。可以理解为多种表现形式,也即“一个对外接口,多个内部实现方法”。在面向对象的理论 中,多态性的一般定义为:同一个操作作用于不同的类的实例,将产生不同的执行结果。也即不同类的对象收到相同的消息时,将得到不同的结果。

在实际的应用开发中,采用面向对象中的多态主要在于可以将不同的子类对象都当作一个父类来处理,并且可以屏蔽不同子类对象之间所存在的差异,写出通用的代码,做出通用的编程,以适应需求的不断变化。

/**
* Shape Interface

* @version 1.0
* @copyright 
* (1)使用接口(interface),你可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。
* (2)我们可以通过interface来定义一个接口,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
* (3)接口中定义的所有方法都必须是public,这是接口的特性
*/

interface Shape {
   public function draw();
}

/**
* Triangle 

* @uses Shape
* @version 1.0
* @copyright
* (1)要实现一个接口,可以使用implements操作符。类中必须实现接口中定义的所有方法,否则 会报一个fatal错误。
* (2)如果要实现多个接口,可以用逗号来分隔多个接口的名称。 
*/
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 多态,php多态 1.什么是多态 多 态(Polymorphism)按字面上意思理解就是多种形状。可以理解为多种表现形式,也即一个对外接口,多个内...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!