继承
继承是一种面向对象编程的概念,它允许我们创建一个新的类,该类从现有的类中继承属性和方法。继承可以减少代码重复,并允许我们构建更复杂的对象层次结构。
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Dog extends Animal {
public function bark() {
echo "Woof!";
}
}
$dog = new Dog("Fido");
echo $dog->getName(); // 输出 "Fido"
$dog->bark(); // 输出 "Woof!"
在上面的例子中,我们定义了一个名为Animal
的类,它有一个名为name
的属性和一个名为getName()
的方法。我们还定义了一个名为Dog
的类,它从Animal
类继承了name
属性和getName()
方法,并添加了一个名为bark()
的方法。
多态性
多态性是面向对象编程的一个概念,它允许我们使用相同的方法来处理不同类型的对象。多态性可以提高代码的灵活性和可扩展性。
class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
public function getColor() {
return $this->color;
}
public function getArea() {
// 抽象方法
}
}
class Rectangle extends Shape {
protected $width;
protected $height;
public function __construct($color, $width, $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function getArea() {
return $this->width * $this->height;
}
}
class Circle extends Shape {
protected $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function getArea() {
return pi() * pow($this->radius, 2);
}
}
$shapes = array(
new Rectangle("red", 5, 10),
new Circle("blue", 3)
);
foreach