1. 面向对象编程(OOP)
PHP 支持面向对象编程,允许你创建类和对象,以实现更好的代码组织和重用。
1.1 类和对象
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function getDescription() {
return "这是一辆 " . $this->color . " " . $this->model;
}
}
$myCar = new Car("红色", "Toyota");
echo $myCar->getDescription(); // 输出 "这是一辆 红色 Toyota"
1.2 继承
子类可以继承父类的属性和方法。
class ElectricCar extends Car {
public $batteryCapacity;
public function __construct($color, $model, $batteryCapacity) {
parent::__construct($color, $model);
$this->batteryCapacity = $batteryCapacity;
}
public function getDescription() {
return parent::getDescription() . ",电池容量为 " . $this->batteryCapacity . " kWh";
}
}
$myElectricCar = new ElectricCar("蓝色", "Tesla", 75);
echo $myElectricCar->getDescription(); // 输出 "这是一辆 蓝色 Tesla,电池容量为 75 kWh"
1.3 接口和抽象类
接口定义了一组方法,而抽象类可以包含实现和未实现的方法。