Understanding inheritance and polymorphism in PHP is crucial for building flexible and scalable applications. Inheritance allows convenient code reuse, while polymorphism enhances program flexibility. Mastering these concepts helps developers design high-quality PHP applications.
To create a derived class, you can use the extends keyword. For example, the following code creates a class named Dog that inherits from the Animal class:
class Dog extends Animal {
public function bark() {
echo "Woof!";
}
}The derived class Dog inherits all properties and methods from the Animal class, allowing access to name, age, and eat(). Additionally, Dog defines its own method bark().
Polymorphism allows treating different types of objects as the same type, making code more general and flexible. It can be implemented via parent classes or interfaces.
For example, define an Animal interface:
interface Animal {
public function eat();
}Then create multiple classes that implement the Animal interface:
class Dog implements Animal {
public function eat() {
echo "The dog eats a bone.";
}
}
class Cat implements Animal {
public function eat() {
echo "The cat eats a mouse.";
}
}
class Bird implements Animal {
public function eat() {
echo "The bird eats a worm.";
}
}Use the same function to operate on different animal objects:
function feedAnimal(Animal $animal) {
$animal->eat();
}
$dog = new Dog();
$cat = new Cat();
$bird = new Bird();
feedAnimal($dog);
feedAnimal($cat);
feedAnimal($bird);Output:
The dog eats a bone. The cat eats a mouse. The bird eats a worm.
Inheritance and polymorphism are core concepts of object-oriented programming in PHP. They help developers build scalable and reusable applications. Inheritance allows new classes to reuse properties and methods of existing classes, while polymorphism enables handling different class objects in a unified way, simplifying code writing and maintenance.