OOP的好处  1.封装, 2继承, 3多态.

多态性是指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息将可以产生不同的结果,这种现象称为多态性。

<?php
// 定义了一个形状的接口,里面有两个抽象方法让子类去实现
interface Shape {
    function area();
    function perimeter();
}

// 定义了一个矩形子类实现了形状接口中的周长和面积
class Rect implements Shape {
    private $width;
    private $height;

    function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    function area() {
        return "矩形的面积是:" . ($this->width * $this->height);
    }

    function perimeter() {
        return "矩形的周长是:" . (2 * ($this->width + $this->height));
    }
}

// 定义了一个圆形子类实现了形状接口中的周长和面积
class  Circular implements Shape {
    private $radius;

    function __construct($radius) {
        $this->radius=$radius;
    }

    function area() {
        return "圆形的面积是:" . (3.14 * $this->radius * $this->radius);
    }

    function perimeter() {
        return "圆形的周长是:" . (2 * 3.14 * $this->radius);
    }
}

// 把子类矩形对象赋给形状的一个引用
$shape = new Rect(5, 10);
echo $shape->area() . "<br>";
echo $shape->perimeter() . "<br>";

// 把子类圆形对象赋给形状的一个引用
$shape = new Circular(10);
echo $shape->area() . "<br>";
echo $shape->perimeter() . "<br>";
View Code

相关文章: