Inheritance in PHP allows a class to acquire the properties and methods of another class. It is a core concept of Object-Oriented Programming that promotes reuse and clean design.
extends keywordA child class inherits all public and protected members of the parent class. Methods can be overridden to provide specific behavior.
// Parent class definition
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
return "Some generic sound";
}
}
// Child class inheriting from Animal
class Dog extends Animal {
public function makeSound() {
return "Woof! Woof!";
}
}
$dog = new Dog("Buddy");
echo $dog->name . " says " . $dog->makeSound();
?>
The Dog class inherits the name property from Animal and overrides the makeSound() method to provide a specific sound.
// Base class for vehicles
<?php
class Vehicle {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function intro() {
return "This is a vehicle of brand: " . $this->brand;
}
}
// Car class extending Vehicle
class Car extends Vehicle {
public function message() {
return "This is a car, brand: " . $this->brand;
}
}
$car = new Car("Toyota");
echo $car->intro();
echo "<br>";
echo $car->message();
?>
Animal → Dog
Vehicle → Car
Child classes automatically gain access to parent functionality and can customize it.
parent::methodName() to call parent logicShape class with an area() methodRectangle classarea() method and print the result
// Simple PHP inheritance output test
<?php
echo "Hello from 10.3 PHP OOP Inheritance";
?>