Inheritance in PHP is the ability of a class (known as a child class or subclass) to derive properties and methods from another class (known as a parent class or base class). Using inheritance, you can extend existing classes and modify or add new functionalities without changing the original code.
Syntax:
class ParentClass {
// Properties and methods
}
class ChildClass extends ParentClass {
// Additional or overridden properties and methods
}
Now, let us understand with the help of the example:
PHP
class Animal {
public $name;
public function eat() {
echo "$this->name is eating.\n";
}
}
class Dog extends Animal {
public function bark() {
echo "$this->name is barking.\n";
}
}
$dog = new Dog();
$dog->name = "Buddy";
$dog->eat();
$dog->bark();
?>
OutputBuddy is eating.
Buddy is barking.
In this example:
- A class Animal is defined with a public property $name and a method eat(), which prints a message indicating the animal is eating.
- A class Dog is defined that extends (inherits from) the Animal class. It adds a new method bark() that prints a message indicating the dog is barking.
- An object $dog of class Dog is created. Since Dog extends Animal, it also has access to the eat() method inherited from the Animal class.
- The $name property of the $dog object is set to the string "Buddy", which is the name of the dog.
- The eat() method of the parent class Animal is called on $dog, and it outputs: "Buddy is eating."
- The bark() method of the Dog class is called on $dog, and it outputs: "Buddy is barking."
Types of Inheritance in PHP
1. Single Inheritance
PHP supports single inheritance, meaning a class can inherit from only one parent class at a time.
PHP
class A {
public function sayHello() {
echo "Hello from A\n";
}
}
class B extends A {
public function sayHi() {
echo "Hi from B\n";
}
}
$objA = new A();
$objA->sayHello();
$objB = new B();
$objB->sayHello();
$objB->sayHi();
?>
OutputHello from A
Hello from A
Hi from B
In this example:
- Class A has a method sayHello(), which prints "Hello from A".
- Class B extends class A, meaning it inherits the method sayHello(). It also defines its own method sayHi() which prints "Hi from B".
- An object $objA of class A is created, and calling sayHello() prints "Hello from A".
- An object $objB of class B is created, which can access sayHello() from class A and sayHi() from class B.
- $objB demonstrates inheritance as it can use both the inherited method and its own method.
- This is an example of single inheritance, where class B inherits from class A.
2. Multilevel Inheritance
In multilevel inheritance, a class inherits from a class, which in turn inherits from another class.
PHP
class A {
public function greet() {
echo "Hello from A\n";
}
}
class B extends A {
public function welcome() {
echo "Welcome from B\n";
}
}
class C extends B {
public function message() {
echo "Message from C\n";
}
}
$objA = new A();
$objA->greet();
$objB = new B();
$objB->greet();
$objB->welcome();
$objC = new C();
$objC->greet();
$objC->welcome();
$objC->message();
?>
OutputHello from A
Hello from A
Welcome from B
Hello from A
Welcome from B
Message from C
In this example:
- Defines a method greet(), which prints "Hello from A".
- Inherits from class A and adds a new method welcome(), which prints "Welcome from B".
- Inherits from class B and adds another method message(), which prints "Message from C".
- $objA can only access greet().
- $objB can access greet() from class A and welcome() from class B.
- $objC can access methods from both A and B and also its own message() method.
- This is multilevel inheritance, where class C inherits from B, and B inherits from A.
3. Multiple Inheritance
PHP does not support multiple inheritance directly through classes, but you can use traits to simulate multiple inheritance.
PHP
trait Logger {
public function log($msg) {
echo "Log: $msg\n";
}
}
trait Auth {
public function authenticate() {
echo "User authenticated\n";
}
}
class User {
use Logger, Auth;
}
$objUser = new User();
$objUser->log("This is a log message.");
$objUser->authenticate();
?>
OutputLog: This is a log message.
User authenticated
In this example:
- Defines a method log(), which prints "Log: [message]".
- Defines a method authenticate(), which prints "User authenticated".
- Uses both Logger and Auth traits, giving it access to both log() and authenticate() methods.
- The object $objUser has access to both methods from the traits, simulating multiple inheritance.
- This is simulated multiple inheritance in PHP using traits, where a class can inherit functionality from more than one source.
Note: PHP does not support multiple inheritance using classes. But you can achieve similar functionality using traits.
4. Hierarchical Inheritance
In PHP, hierarchical inheritance occurs when multiple child classes inherit from a single parent class.
PHP
class Employee {
public $name;
public $position;
public function __construct($name, $position) {
$this->name = $name;
$this->position = $position;
}
public function introduce() {
echo "I am {$this->name}, and I work as a {$this->position}.";
}
}
class Manager extends Employee {
public $team;
public function __construct($name, $position, $team) {
parent::__construct($name, $position);
$this->team = $team;
}
public function introduce() {
echo "I am {$this->name}, I work as a {$this->position}, and I manage the {$this->team} team.";
}
}
class Developer extends Employee {
public $programmingLanguage;
public function __construct($name, $position, $programmingLanguage) {
parent::__construct($name, $position);
$this->programmingLanguage = $programmingLanguage;
}
public function introduce() {
echo "I am {$this->name}, I work as a {$this->position}, and I specialize in {$this->programmingLanguage}.";
}
}
$manager = new Manager("kriti", "Manager", "Sales");
$developer = new Developer("Ayushi", "Developer", "PHP");
$manager->introduce();
$developer->introduce();
?>
OutputI am kriti, I work as a Manager, and I manage the Sales team.I am Ayushi, I work as a Developer, and I specialize in PHP.
In this example:
- The Employee class defines properties like $name and $position, and a method introduce() that outputs the employee's details.
- The Manager and Developer classes both extend the Employee class.
- Both child classes call the parent constructor using parent::__construct() to initialize the common properties (name and position).
- Each child class overrides the introduce() method to provide more specific information related to their roles (team for Manager, programming language for Developer).
- Objects of the Manager and Developer classes are created, and the introduce() method is called for each, showing how hierarchical inheritance works.
- This demonstrates hierarchical inheritance, where both the Manager and Developer classes inherit from the Employee class, but have different implementations of the introduce() method.
Constructor in Inheritance
If the parent class has a constructor, the child class must explicitly call it using parent::__construct().
class Person {
public function __construct($name) {
echo "Person: $name\n";
}
}
class Student extends Person {
public function __construct($name, $rollNo) {
parent::__construct($name);
echo "Student Roll No: $rollNo\n";
}
}
Overriding Inherited Methods in PHP
In PHP, you can override inherited methods by redefining them in the child class with the same name. This allows the child class to modify the behavior of the inherited methods while still retaining the structure of the parent class.
class Vehicle {
public $brand;
public $model;
// Parent class constructor
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
}
// Parent class method
public function description() {
echo "This is a vehicle of brand {$this->brand} and model {$this->model}.";
}
}
class Car extends Vehicle {
public $fuelType;
// Child class constructor
public function __construct($brand, $model, $fuelType) {
$this->brand = $brand;
$this->model = $model;
$this->fuelType = $fuelType;
}
// Overriding the description method in the child class
public function description() {
echo "This is a car of brand {$this->brand}, model {$this->model}, and it runs on {$this->fuelType} fuel.";
}
}
// Creating an object of the Car class
$car = new Car("Toyota", "Corolla", "Petrol");
$car->description(); // Output: This is a car of brand Toyota, model Corolla, and it runs on Petrol fuel.
?>
In this code:
- The Vehicle class has two properties: $brand and $model, which are initialized using the constructor.
- The description() method is defined to output a general description of the vehicle (brand and model).
- The Car class extends Vehicle, meaning it inherits the properties and methods from the Vehicle class.
- The constructor in Car overrides the parent constructor to also initialize the $fuelType property.
- The description() method is overridden in the Car class to provide more specific details about the car, including the fuel type.
- When you create an object of the Car class and call the description() method, the overridden method in Car is executed, outputting a more detailed description than the one in Vehicle.
The final Keyword
In PHP, the final keyword is used to prevent class inheritance or method overriding. When applied to a class or a method, it restricts further modification or extension.
1. Preventing Class Inheritance
You can prevent a class from being extended by marking the class as final. Any attempt to extend a final class will result in an error.
final class Cars {
// some code
}
// will result in error
class Honda extends Cars {
// some code
}
?>
In this example:
- The Car class is marked as final, meaning no class can extend it (such as Honda).
- Attempting to create a subclass (Honda) that extends Car will result in a fatal error because Car is a final class and cannot be inherited.
2. Preventing Method Overriding (Using final on a Method)
The final keyword can also be applied to methods to prevent them from being overridden by child classes.
class Animal {
// Marking the method as final to prevent overriding
final public function sound() {
echo "This animal makes a sound.";
}
}
class Dog extends Animal {
// This will result in an error, as sound() is final in the parent class
public function sound() {
echo "Bark!";
}
}
?>
In this example:
- The sound() method in the Animal class is marked as final. This means that no child class (e.g., Dog) can override the sound() method.
- If the Dog class tries to redefine the sound() method, a fatal error will occur because the method is final in the parent class.
Benefits of Inheritance
- Code Reusability: Reduces code duplication by reusing existing code.
- Scalability: Easier to scale and maintain applications.
- Extensibility: Easily add new functionalities without modifying existing code.
Similar Reads
PHP Introduction PHP stands for Hypertext Preprocessor. It is an open-source, widely used language for web development. Developers can create dynamic and interactive websites by embedding PHP code into HTML. PHP can handle data processing, session management, form handling, and database integration. The latest versi
8 min read
PHP | exit( ) Function The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called. The message
2 min read
Introduction to PHP8 Back in the mid-1990s, PHP started as a Personal Home Page, but now it's known as Hypertext Preprocessor. It's a widely used scripting language that is perfect for web development and can easily be inserted into HTML. Over time, PHP has become super powerful for making dynamic and engaging web apps.
5 min read
PHP File Handling In PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
4 min read
Interesting Facts About PHP PHP is a widely-used open source and general purpose scripting language which is primarily made for web development. It can be merged into the HTML. Here are some interesting facts about PHP: The mascot of PHP is a big blue elephant.âPersonal Home Pageâ is the original name of PHP.Today, PHP is reco
2 min read
PHP Array Functions Arrays are one of the fundamental data structures in PHP. They are widely used to store multiple values in a single variable and can store different types of data, such as strings, integers, and even other arrays. PHP offers a large set of built-in functions to perform various operations on arrays.
7 min read
PHP vs HTML What is PHP? PHP stands for Hypertext Preprocessor. PHP is a server-side, scripting language (a script-based program) and is used to develop Web applications. It can be embedded in HTML, and it's appropriate for the creation of dynamic web pages and database applications. It's viewed as a benevolent
2 min read
PHP file_get_contents() Function In this article, we will see how to read the entire file into a string using the file_get_contents() function, along with understanding their implementation through the example.The file_get_contents() function in PHP is an inbuilt function that is used to read a file into a string. The function uses
3 min read
PHP Date and Time PHP provides functions to work with dates and times, allowing developers to display the current date/time, manipulate and format dates, and perform operations like date comparisons, time zone adjustments, and more.In this article, we'll discuss PHP date and time.Why are Date and Time Important in PH
5 min read
Common Mistakes to Avoid in PHP PHP is a widely used server-side scripting language for web development. However, developers often overlook best practices, leading to vulnerabilities and inefficiencies. This article delves into common PHP mistakes and offers comprehensive solutions. Table of Content Not Using Prepared StatementsIg
2 min read