在PHP中,继承和多态是面向对象编程(OOP)的两大核心概念。继承允许一个类(子类)继承另一个类(父类)的属性和方法,从而实现代码复用和扩展。多态则允许不同类的对象对同一消息做出不同的响应,增强代码的灵活性和可扩展性。
在PHP中,继承是通过使用extends关键字来实现的。父类定义了共通的属性和方法,子类可以继承这些属性和方法,也可以添加新的属性和方法或者重写父类的方法。
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
return "I am an animal.";
}
}
class Dog extends Animal {
public function speak() {
return "Woof!";
}
}
class Cat extends Animal {
public function speak() {
return "Meow!";
}
}
$dog = new Dog("Buddy");
$cat = new Cat("Whiskers");
echo $dog->speak(); // 输出: Woof!
echo $cat->speak(); // 输出: Meow!
?>
在这个示例中,Animal是父类,定义了一个属性name和一个方法speak()。Dog和Cat是子类,它们继承了Animal类的属性和方法,并且重写了speak()方法以提供特定的行为。
多态在PHP中通常通过方法重写(在子类中重写父类的方法)和接口实现(使用implements关键字实现一个或多个接口)来实现。
<?php
interface Shape {
public function calculateArea();
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function calculateArea() {
return $this->width * $this->height;
}
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
function printArea(Shape $shape) {
echo "The area is: " . $shape->calculateArea() . "\n";
}
$rectangle = new Rectangle(4, 5);
$circle = new Circle(3);
printArea($rectangle); // 输出: The area is: 20
printArea($circle); // 输出: The area is: 28.274333882308
?>
在这个示例中,Shape是一个接口,定义了一个方法calculateArea()。Rectangle和Circle类实现了Shape接口,并提供了各自的calculateArea()方法的实现。printArea()函数接受一个Shape接口类型的参数,可以接受任何实现了Shape接口的类的对象,从而实现了多态。
通过继承,我们可以创建具有共同属性和方法的类层次结构,从而提高代码的复用性和可维护性。通过多态,我们可以编写更加灵活和可扩展的代码,因为不同的类可以以不同的方式响应相同的消息。