In object-oriented programming, inheritance is a key mechanism for code reuse and extension. It allows a child class to inherit properties and methods from its parent class, reducing code duplication and creating cleaner, more organized structures.
class Person {
protected $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
class Student extends Person {
private $school;
public function __construct($name, $age, $school) {
parent::__construct($name, $age);
$this->school = $school;
}
public function getSchool() {
return $this->school;
}
}
$student = new Student("John Doe", 20, "Harvard University");
echo $student->getName(); // John Doe
echo $student->getAge(); // 20
echo $student->getSchool(); // Harvard UniversityIn this example, the Person class serves as a parent class with shared logic, while the Student class extends it by adding a new property $school. This allows the subclass to reuse existing logic while adding its own unique functionality.
Polymorphism allows different classes to define their own implementations of the same method interface, giving programs flexibility and scalability. In PHP, this is usually achieved through method overriding.
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function speak() {
echo "Animal speaks.";
}
}
class Cat extends Animal {
public function speak() {
echo "Meow!";
}
}
class Dog extends Animal {
public function speak() {
echo "Woof!";
}
}
$animals = [new Cat("Kitty"), new Dog("Buddy")];
foreach ($animals as $animal) {
echo $animal->getName() . ": ";
$animal->speak();
echo "<br>";
}This example demonstrates polymorphism in action. Both Cat and Dog inherit from Animal but override the speak() method with their own behavior. When looping through the $animals array, each object responds differently to the same method call, showcasing the dynamic nature of polymorphism.
In real-world PHP development, inheritance and polymorphism are crucial for writing modular, maintainable, and scalable code. Common use cases include:
Inheritance and polymorphism are two fundamental principles of PHP’s object-oriented programming model. Inheritance promotes code reuse and structure, while polymorphism enables flexibility and extensibility. Mastering these concepts allows developers to create cleaner, more maintainable, and scalable PHP applications.