继承是面向对象编程的重要机制,它允许一个类基于另一个类创建新类,子类可以继承父类的属性和方法,从而实现代码复用和扩展。在PHP中,关键字extends用于创建子类,而parent::则用于调用父类的成员方法或属性。
class Animal {
protected $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getInfo() {
return "Name: " . $this->name . ", Age: " . $this->age;
}
}
class Dog extends Animal {
public function bark() {
return "Woof!";
}
}
$dog = new Dog("Rex", 3);
echo $dog->getInfo(); // 输出 "Name: Rex, Age: 3"
echo $dog->bark(); // 输出 "Woof!"
以上代码展示了一个动物基类Animal,它拥有name和age属性及获取信息的方法。子类Dog继承了这些属性和方法,并新增了bark()方法,体现了继承的基本用法。
多态指的是同一接口或方法在不同类的对象中展现出不同的行为。在PHP中,多态主要通过接口(interface)和抽象类(abstract class)实现。接口定义了方法规范,而抽象类则提供部分实现,子类必须具体实现抽象方法。这样可以使代码更加灵活和可扩展。
interface Shape {
public function area();
public function perimeter();
}
class Rectangle implements Shape {
private $length;
private $width;
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}
public function area() {
return $this->length * $this->width;
}
public function perimeter() {
return 2 * ($this->length + $this->width);
}
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * pow($this->radius, 2);
}
public function perimeter() {
return 2 * pi() * $this->radius;
}
}
$rectangle = new Rectangle(5, 3);
$circle = new Circle(2);
echo $rectangle->area(); // 输出 15
echo $rectangle->perimeter(); // 输出 16
echo $circle->area(); // 输出 12.566370614359
echo $circle->perimeter(); // 输出 12.566370614359
在示例中,Rectangle和Circle都实现了Shape接口,必须定义area()和perimeter()方法。不同的实现使同一方法具有不同的行为,这正是多态的体现。
继承和多态是PHP面向对象编程的基础,掌握这两者可以大大提升代码的组织性和复用性。继承允许子类获得父类的属性和方法,避免重复代码;多态通过接口或抽象类让同一方法在不同对象中表现出多样行为,从而增强代码的灵活性。本文提供的示例代码适合初学者理解这些概念,助力开发更高质量的PHP程序。