Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a class (subclass or child class) to inherit properties and methods from another class (superclass or parent class). This promotes code reusability and the creation of a hierarchy of classes. In PHP, inheritance is achieved using the extends keyword.
class ChildClass extends ParentClass {
// Child class properties and methods
}
Example of Inheritance:
Here's an example to illustrate how inheritance works in PHP:
class Vehicle {
public $brand;
public $model;
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
}
public function displayInfo() {
echo "Brand: {$this->brand}, Model: {$this->model}<br>";
}
}
// Car class inherits from Vehicle
class Car extends Vehicle {
public function drive() {
echo "{$this->brand} {$this->model} is driving.<br>";
}
}
// Motorcycle class inherits from Vehicle
class Motorcycle extends Vehicle {
public function ride() {
echo "{$this->brand} {$this->model} is riding.<br>";
}
}
// Creating objects of the derived classes
$car = new Car("Toyota", "Camry");
$motorcycle = new Motorcycle("Honda", "CBR");
// Calling methods from the parent class
$car->displayInfo(); // Output: Brand: Toyota, Model: Camry
$car->drive(); // Output: Toyota Camry is driving.
$motorcycle->displayInfo(); // Output: Brand: Honda, Model: CBR
$motorcycle->ride(); // Output: Honda CBR is riding.
In this example:
Within a child class, you can call methods from the parent class using the parent:: syntax.
Example:
class Animal {
public function makeSound() {
echo "Animal makes a sound.<br>";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Dog barks.<br>";
parent::makeSound(); // Call parent class method
}
}
$dog = new Dog();
$dog->makeSound();
// Output:
// Dog barks.
// Animal makes a sound.
When a child class defines a method with the same name as a method in its parent class, the method in the child class overrides (replaces) the method in the parent class. This allows for customization of behavior in the child class.
class Animal {
public function makeSound() {
echo "Animal makes a sound.<br>";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Dog barks.<br>";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Dog barks.
Inheritance is a powerful feature in PHP OOP that allows classes to inherit properties and methods from other classes. It promotes code reusability and helps create a hierarchy of classes. Child classes can extend the functionality of parent classes, override parent class methods, and provide specialized behavior. Understanding inheritance is essential for building flexible and maintainable object-oriented PHP applications.