多态是面向对象编程中的重要概念,它允许不同的对象对同一个方法做出不同的响应。在PHP中,多态可以通过继承和接口来实现。
以下是一些PHP多态面向对象编程的高级实践:
interface Shape {
public function area();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * pow($this->radius, 2);
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function area() {
return $this->width * $this->height;
}
}
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";
}
}
$animals = [new Dog(), new Cat()];
foreach ($animals as $animal) {
$animal->speak();
}
function calculateArea(Shape $shape) {
return $shape->area();
}
$circle = new Circle(5);
$rectangle = new Rectangle(3, 4);
echo calculateArea($circle) . "\n";
echo calculateArea($rectangle) . "\n";
通过以上高级实践,可以更好地利用PHP的面向对象编程特性,实现更灵活和可扩展的代码结构。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。