php 面向对象编程可通过扩展和定制类实现扩展。扩展类通过继承父类属性和方法,并可添加新属性和方法;定制类则通过实现接口的方法来实现特定功能。实战案例中,通过扩展抽象类 shape,创建了 circle 和 rectangle 等具体形状,可动态计算面积。

PHP 面向对象编程:扩展和定制
面向对象编程 (OOP) 允许您创建可重用、可维护的代码。在 PHP 中,OOP 可以通过扩展和定制现有类来进一步扩展。
扩展类
立即学习“PHP免费学习笔记(深入)”;
使用 extends 关键字可以扩展一个类。扩展后的类继承父类的所有属性和方法,并可以添加新属性和方法。
class BaseClass {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class ExtendedClass extends BaseClass {
private $age;
public function __construct($name, $age) {
parent::__construct($name);
$this->age = $age;
}
public function getAge() {
return $this->age;
}
}定制类
使用 implements 关键字可以定制一个类,让它实现一个或多个接口。接口定义了一组方法,该类必须实现这些方法。
interface MyInterface {
public function doSomething();
}
class MyClass implements MyInterface {
public function doSomething() {
// 具体实现
}
}实战案例
考虑一个抽象类 Shape,它定义了一个 getArea() 方法。我们扩展此类以创建具体形状,例如 Circle 和 Rectangle。
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function getArea();
}
class Circle extends Shape {
private $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function getArea() {
return pi() * $this->radius ** 2;
}
}
class Rectangle extends Shape {
private $width;
private $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}我们可以创建 Circle 和 Rectangle 对象并访问它们各自的 getArea() 方法,从而动态地计算面积。
以上就是PHP面向对象编程的深入理解:面向对象编程的扩展和定制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号