PHP面向对象三大特性之多态基础

来源:互联网 发布:写作软件app 编辑:程序博客网 时间:2024/05/17 01:24

多态是除封装继承之外的另一个面象对象的三大特性之一。

[php] view plain copy
  1. <?php  
  2. interface Shape  
  3.     {  
  4.         function area();  
  5.         function perimeter();  
  6.     }      
  7.       
  8.         //定义了一个矩形子类实现了形状接口中的周长和面积  
  9.     class Rect implements Shape  
  10.     {  
  11.         private $width;  
  12.         private $height;  
  13.         function __construct($width$height) {  
  14.             $this->width = $width;  
  15.             $this->height = $height;  
  16.         }      
  17.         function area() {  
  18.             return "矩形的面积是:" . ($this->width * $this->height);  
  19.         }  
  20.         function perimeter() {  
  21.             return "矩形的周长是:" . (2 * ($this->width + $this->height));  
  22.         }      
  23.     }     
  24.   
  25.     //定义了一个圆形子类实现了形状接口中的周长和面积  
  26.     class  Circular implements Shape  
  27.     {  
  28.         private $radius;       
  29.         function __construct($radius) {  
  30.             $this->radius=$radius;  
  31.         }   
  32.         function area() {  
  33.             return "圆形的面积是:" . (3.14 * $this->radius * $this->radius);  
  34.         }      
  35.         function perimeter() {  
  36.             return "圆形的周长是:" . (2 * 3.14 * $this->radius);  
  37.         }  
  38.     }      
  39.       
  40.         //把子类矩形对象赋给形状的一个引用  
  41.     $shape = new Rect(5, 10);  
  42.     echo $shape->area() . "<br>";  
  43.     echo $shape->perimeter() . "<br>";  
  44.        
  45.   
  46.     //把子类圆形对象赋给形状的一个引用  
  47.     $shape = new Circular(10);  
  48.     echo $shape->area() . "<br>";  
  49.     echo $shape->perimeter() . "<br>";*/  
输出结果:

[php] view plain copy
  1. 矩形的面积是:50  
  2. 矩形的周长是:30  
  3. 圆形的面积是:314  
  4. 圆形的周长是:62.8  

通过上例我们看到,把矩形对象和圆形对象分别赋给了变量$shape, 调用$shape引用中的面积和周长的方法,出现了不同的结果,这就是一种多态的 应用,其实在我们PHP这种弱类形的面向对象的语言里面,多态的特性并不是特别的明显,其实就是对象类型变量的变相引用。
原创粉丝点击