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
<?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
<?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
<?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
<?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
<?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.
<?php
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.
<?php
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.
<?php
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 Tutorial PHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
9 min read
Basics
PHP SyntaxPHP, a powerful server-side scripting language used in web development. Itâs simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
4 min read
PHP VariablesA variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
5 min read
PHP | FunctionsA function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
PHP LoopsIn PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
4 min read
Array
PHP ArraysArrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
PHP Associative ArraysAn associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
4 min read
Multidimensional arrays in PHPMulti-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
5 min read
Sorting Arrays in PHPSorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
4 min read
OOPs & Interfaces
MySQL Database
PHP | MySQL Database IntroductionWhat is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
4 min read
PHP Database connectionThe collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
2 min read
PHP | MySQL ( Creating Database )What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
3 min read
PHP | MySQL ( Creating Table )What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
3 min read
PHP Advance
PHP SuperglobalsPHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
6 min read
PHP | Regular ExpressionsRegular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
12 min read
PHP Form HandlingForm handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the dataâeither through the POST method (more secure, hid
4 min read
PHP File HandlingIn 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
PHP | Uploading FileHave you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
3 min read
PHP CookiesA cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
9 min read
PHP | SessionsA session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
7 min read