PHP面向对象的多态性是指在面向对象编程中,同一个方法可以根据不同的对象类型产生不同的行为。在PHP中,多态性可以通过继承和接口来实现。
class Animal {
public function speak() {
echo "Animal speaks";
}
}
class Dog extends Animal {
public function speak() {
echo "Dog barks";
}
}
class Cat extends Animal {
public function speak() {
echo "Cat meows";
}
}
$animal = new Animal();
$dog = new Dog();
$cat = new Cat();
$animal->speak(); // 输出 "Animal speaks"
$dog->speak(); // 输出 "Dog barks"
$cat->speak(); // 输出 "Cat meows"
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return 3.14 * $this->radius * $this->radius;
}
}
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;
}
}
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);
echo $circle->calculateArea(); // 输出 "78.5"
echo $rectangle->calculateArea(); // 输出 "24"
通过继承和接口,PHP面向对象的多态性可以实现代码的灵活性和可扩展性,使得同一个方法可以根据不同的对象类型产生不同的行为。
下一篇:如何使用PHP处理多重表单提交
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站