PHP 函数的抽象和继承

php 中抽象函数仅声明函数签名,由子类实现;继承允许子类继承父类属性和方法。通过抽象类 shape 和继承子类 rectangle 和 circle,可以创建不同形状并计算其面积,如示例中所示的矩形和圆形。PHP 函数的抽象和继承
抽象函

php 中抽象函数仅声明函数签名,由子类实现;继承允许子类继承父类属性和方法。通过抽象类 shape 和继承子类 rectangle 和 circle,可以创建不同形状并计算其面积,如示例中所示的矩形和圆形。

PHP 函数的抽象和继承

PHP 函数的抽象和继承

抽象函数

抽象函数只声明函数签名,但没有提供实现。子类必须实现抽象函数,否则将出现错误。

abstract class Shape {
    abstract public function getArea();
}

登录后复制

继承

PHP 支持类的继承,允许子类继承父类的属性和方法。

class Rectangle extends Shape {
    private $width;
    private $height;

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

    public function getArea() {
        return $this->width * $this->height;
    }
}

登录后复制

实战案例

创建一个计算不同形状面积的程序:

abstract class Shape {
    abstract public function getArea();
}

class Rectangle extends Shape {
    private $width;
    private $height;

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

    public function getArea() {
        return $this->width * $this->height;
    }
}

class Circle extends Shape {
    private $radius;

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

    public function getArea() {
        return pi() * $this->radius ** 2;
    }
}

// 创建不同的形状对象
$rectangle = new Rectangle(5, 10);
$circle = new Circle(10);

// 计算并打印它们的面积
echo "矩形面积:{$rectangle->getArea()}n";
echo "圆形面积:{$circle->getArea()}n";

登录后复制

输出:

矩形面积:50
圆形面积:314.1592653589793

登录后复制

以上就是PHP 函数的抽象和继承的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:张大嘴,转转请注明出处:https://www.dingdanghao.com/article/714282.html

(0)
上一篇 2024-08-12 16:28
下一篇 2024-08-12 16:28

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号