PHP Inheritance
Learn about inheritance in PHP, a fundamental concept in object-oriented programming that promotes code reuse and organization.
Introduction to Inheritance
Inheritance is a mechanism where a new class (child class or subclass) can inherit properties and methods from an existing class (parent class or superclass). This allows for code reuse and the creation of a hierarchical class structure.
Benefits of Inheritance
- Code Reusability: You can reuse existing code without rewriting it.
- Method Overriding: Child classes can provide specific implementations of methods defined in parent classes.
- Easy Maintenance: Changes made in the parent class automatically reflect in child classes.
Creating a Parent Class
To create a parent class, simply define a class with properties and methods that you want to be inherited:
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
return "Some generic animal sound";
}
}
?>
Creating a Child Class
To create a child class, use the extends
keyword to inherit from the parent class:
<?php
class Dog extends Animal {
public function makeSound() {
return "Woof! My name is {$this->name}.";
}
}
$dog = new Dog("Buddy");
echo $dog->makeSound(); // Outputs: Woof! My name is Buddy.
?>
Constructor Inheritance
Child classes can call the parent class's constructor using the parent::
keyword:
<?php
class Cat extends Animal {
public function __construct($name) {
parent::__construct($name); // Calling parent constructor
}
public function makeSound() {
return "Meow! My name is {$this->name}.";
}
}
$cat = new Cat("Whiskers");
echo $cat->makeSound(); // Outputs: Meow! My name is Whiskers.
?>
Accessing Parent Class Properties and Methods
Child classes can access public and protected properties and methods of the parent class:
<?php
class Bird extends Animal {
public function getName() {
return $this->name; // Accessing public property
}
}
$bird = new Bird("Tweety");
echo $bird->getName(); // Outputs: Tweety
?>
Conclusion
Inheritance is a powerful feature of PHP that allows for efficient code organization and reuse. By creating parent and child classes, developers can build a structured and maintainable codebase.