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

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; }}
实战案例
创建一个计算不同形状面积的程序:
立即学习“PHP免费学习笔记(深入)”;
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 函数的抽象和继承的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1244466.html
微信扫一扫
支付宝扫一扫