Inheritance is a crucial concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. In PHP, inheritance enables developers to create hierarchical relationships between classes, promoting code reuse and enhancing modularity.
In PHP, inheritance is implemented using the extends
keyword. A class that inherits from another class is called a child class or subclass, while the class being inherited from is referred to as the parent class or superclass.
class ParentClass {
// Parent class properties and methods
}
class ChildClass extends ParentClass {
// Child class properties and methods
}
When a child class extends a parent class, it inherits all the public and protected properties and methods of the parent class. Private members of the parent class are not directly accessible in the child class.
parent::
keyword allows child classes to access parent class methods.Let's look at a practical example of inheritance in PHP:
class Vehicle {
protected $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function startEngine() {
return "The {$this->brand} engine is starting.";
}
}
class Car extends Vehicle {
private $model;
public function __construct($brand, $model) {
parent::__construct($brand);
$this->model = $model;
}
public function getInfo() {
return "This is a {$this->brand} {$this->model}.";
}
}
$myCar = new Car("Toyota", "Corolla");
echo $myCar->startEngine(); // Outputs: The Toyota engine is starting.
echo $myCar->getInfo(); // Outputs: This is a Toyota Corolla.
In this example, the Car
class inherits from the Vehicle
class. It can use the startEngine()
method from the parent class and also defines its own getInfo()
method.
PHP inheritance is a powerful feature that enhances code organization and reusability in object-oriented programming. By understanding and properly implementing inheritance, developers can create more efficient, maintainable, and scalable PHP applications.
To further expand your PHP OOP knowledge, explore related concepts such as PHP Constructors, PHP Access Modifiers, and PHP Traits.