• 跟着百度学PHP[4]OOP面对对象编程-17-多态


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

    多态的作用简而言之就是为程序做括展

    比如说在公司上班,每个月财务发放工资,同一个发工资的方法,在公司内不同的员工或是不同职位的员工,都是通过这个方法发放的,但是所发的工资都是不相同的。所以同一个发工资的方法就出现了多种形态。

    <?php 
    /**
    * 使用多态计算矩形的周长面积。以及圆形的面积跟周长。
    */
    interface test{  #声明一个test接口
        function zhouchang(); #声明一个zhouchang方法
        function mianji(); 
    }
    # 矩形
    class juxing implements test
    {
        private $width;
        private $height;
        
        function __construct($width,$height)
        {
            $this->width = $width; #将输入的值(即"宽")赋值给$this->width
            $this->height = $height;
        }
        function zhouchang(){
            echo "矩形的周长:" .($this->width + $this->height)."<br />";
        }
        function mianji(){
            echo "矩形的面积:".($this->width * $this->height)."<br />";
        }
    }
    # 圆形
    class yuanxing implements test #和矩形的一样的。不做讲解。
    {
        private $r;
        
        function __construct($r)
        {
            $this->r = $r;
        }
        function zhouchang(){
            echo "圆形的周长:".(2 * 3.14 * $this->r)."<br />";
        }
        function mianji(){
            echo "圆形的面积:".(3.14 * $this->r * $this->r."<br />");
        }
    }
    $a = new juxing(1,2);
    $a -> mianji();
    $b = new yuanxing(1,2);
    $b -> zhouchang();
    
     ?>
    输出效果如下所示:
    矩形的面积:2
    圆形的周长:6.28
  • 相关阅读:
    windows常用命令行总结
    express安装
    MySQL去除外键关联关系
    c#实体转化
    C#之Clone
    mysql 将null转代为0(转)
    Mysql显示行号
    mysql存储过程游标加计划任务事件调度器
    mysql临时表
    Git学习笔记
  • 原文地址:https://www.cnblogs.com/xishaonian/p/6206710.html
Copyright © 2020-2023  润新知