• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • PHP Introduction
  • PHP Install
  • PHP Syntax
  • PHP Comments
  • PHP Variables
  • PHP Echo / Print
  • PHP Data Types
  • PHP Strings
  • PHP Constants
  • PHP Operators
  • PHP If...Else...Elseif
  • PHP Switch
  • PHP Loops
  • PHP Functions
  • PHP Arrays
  • PHP Superglobals
  • PHP Date and Time
  • PHP Include
  • PHP File Handling
  • PHP File Upload
  • PHP Cookies
  • PHP Sessions
  • PHP Filters
  • PHP Callback Functions
  • PHP JSON
  • PHP Exceptions
  • PHP What is OOP
  • PHP Classes/Objects
  • PHP Constructor
  • PHP Destructor
  • PHP Access Modifiers
  • PHP Inheritance
  • PHP Abstract Classes
  • PHP Interfaces
  • PHP Traits
  • PHP Static Methods
  • PHP Namespaces
Home >> php >> PHP Inheritance

PHP Inheritance

This tutorial helps you learn about PHP inheritance that lets you reuse the code from another class. So, let us begin!

 

What is PHP Inheritance?

PHP Inheritance enables a class to use properties and methods of another class without duplicating it. Often, we are required to create a new class with all the functionalities of an existing class and some additional functionalities; basically, this new class is more like an extension of an existing class. In such cases, you have two options. First, copy all the properties and methods of the existing class into the new class and use them in the new class; secondly, you can inherit the old class in the new class.

Let us understand this using an example. First, assume a class Human with basic methods and properties in it such as eat(), walk(), see(), hear(), etc. Now, suppose you want to create two more classes for male and female with the name Male and Female, respectively, along with all the properties and methods of the class Human and some additional features available only for Male and Female. In that case, we can do so by inheriting the Human class in the Male and Female classes.

The inherited class is referred to as the Parent class(or super class or base class), while the class inheriting another class is called the Child class(or sub class or derived class).

In the above-mentioned example, Human will be the parent class, and Male and Female will be its child classes.

 

A class can be inherited by multiple classes.

 

Inheritance is beneficial if you need to create several similar classes. You can put the common properties and methods in one parent class and then inherit them in the child classes.

You can use the Destructor method for destroying the object.

 

Syntax for Inheriting a Class

In PHP, you can use extends keyword for specifying the parent class's name while defining the child class. For example,

<?php
    class Human {
        // parent class code
    }
    
    class Male extends Human {
        // child class code
    }
    
    class Female extends Human {
        // child class code
    }
?>

 

Points to remember while using inheritance:

  • Only non-private properties and methods of the parent class can be used and accessed by a Child class.
  • A child class may have its own properties and methods, which are unavailable to the parent class.
  • A method defined in the parent class can be overridden by a child class. In addition, a child class can also provide its own implementation for it.

 

In the above-mentioned example, let's add a few methods to our Human class and see how these can be used in the child classes Male and Female.

<?php
    // parent class
    class Human {
        // public property name
        public $name;
        
        // public function walk
        public function walk() {
            echo $this->name. " is walking...<br/>";
        }
        
        // public function see
        public function see() {
            echo $this->name. " is seeing...<br/>";
        }
    }
    
    // child class
    class Male extends Human {
        // No code in child
    }
    
    // child class
    class Female extends Human {
        // No code in child
    }
    
    $male = new Male();
    $male->name = "Adam";
    
    $female = new Female();
    $female->name = "Eve";
    
    // calling Human class methods
    // check the output (hehe, pun intended)
    $female->walk();
    $male->see();
    
?>

Output:

Eve is walking...
Adam is seeing...

 

As seen in the code above, both the child classes were empty; only class Human was inherited in both of them, which enabled the child classes to access and use the member properties on the parent class.

 

Child Class with its Own Methods and Properties

If a child class inherits a parent class, all the non-private members of the parent class can be accessed and used by the child class. But a child class can have its own member properties and methods. Let us see how we can do it through another example:

<?php
    // parent class
    class Vehicle {
        // public property name
        public $name;
        
        // public function start
        public function start() {
            echo $this->name. " - Engine start...<br/>";
        }
        
        // public function stop
        public function stop() {
            echo $this->name. " - Engine stop...<br/>";
        }
    }
    
    // child class
    class Car extends Vehicle {
        
        public function drive() {
            echo "I am " . $this->name . "<br/>";
            echo "Lets go on a drive...";
        }
        
    }
    
    // child class
    class Motorcycle extends Vehicle {
        
        // motorcycle specific properties
        // and methods
        
    }
    
    $car = new Car();
    $car->name = "Mercedes benz";
    
    // calling parent class method
    $car->start();
    
    // calling child class method
    $car->drive();
    
?>

Output:

Mercedes benz - Engine start...
I am Mercedes benz
Lets go on a drive...

 

The advantage a class gets on inheriting another class is the ability to use the properties and methods of the parent class without defining them again. Moreover, the child class can also have properties and methods of its own, just like any other normal class.

 

The protected Access Modifier

We learned how to use the various access modifiers to control access for various properties and methods of a class.

When a parent class is inherited by a child class, it can only access and reuse the non-private properties and methods of a parent class. But the public access modifiers should not be used for the properties; because the properties can then be accessed from outside the class too.

The protected access modifiers can be used to allow only the child class to access the parent class's properties and methods.

When the property or method of a class has been defined as protected, then those properties and methods are only accessible within the child class which inherits the parent class.

Example:

<?php
    // parent class
    class Vehicle {
        // protected property name
        protected $name;
        
        // public function start
        public function start() {
            echo $this->name. " - Engine start...<br/>";
        }
        
        // public function stop
        public function stop() {
            echo $this->name. " - Engine stop...<br/>";
        }
    }
    
    // child class
    class Car extends Vehicle {
        
        public function drive() {
            // accessing name variable of Car class
            echo "I am " . $this->name . "<br/>";
            echo "Lets go on a drive...";
        }
        
    }
    
    
    $car = new Car();
    $car->name = "Mercedes benz";
    
    // calling parent class method
    $car->start();
    
    // calling child class method
    $car->drive();
    
?>

Output:

Mercedes benz - Engine start...
I am Mercedes benz
Lets go on a drive...

 

In the above-mentioned example, we have made the name variable as protected. Now, try to run the same code with the name as private, and you will get the following error:

Notice: Undefined Property...

 

Overriding Parent class Method

In Method Overriding, a child class can use a parent class method with slight differences by overriding the definition of the method that has been defined in the parent class and providing its own definition. 

Let's understand this concept through an example:

<?php
    // parent class
    class Vehicle {
        // public property name
        public $name;
        
        // public method
        public function drive() {
            echo "Vehicle class drive method...<br/>";
        }
    }
    
    // child class
    class Car extends Vehicle {
        
        public function drive() {
            echo "Car class drive method...<br/>";
        }
        
    }
    
    // child class
    class Motorcycle extends Vehicle {
        
        public function drive() {
            echo "Motorcycle class drive method...<br/>";
        }
        
    }
    
    $car = new Car();
    $car->name = "Mercedes benz";
    
    // calling child class method
    $car->drive();
    
    $bike = new Motorcycle();
    $bike->name = "Triumph Tiger";
    
    // calling child class method
    $bike->drive();
    
?>

Output:

Car class drive method...
Motorcycle class drive method...

 

There is a parent class named Vehicle in the above-mentioned code and two child classes extending the parent class named Car and Motorcycle. In addition, there is a method drive () in the parent class that we have overridden in the child classes and have defined a different definition to it.

In case you do not want any child class to override the parent class method, then you can define the method in the parent class as final.

Now, let us see what happens if we try to override a final method.

<?php
    // parent class
    class Vehicle {
        // public property name
        public $name;
        
        // public method
        final public function drive() {
            echo "Vehicle class drive method...<br/>";
        }
    }
    
    // child class
    class Car extends Vehicle {
        
        public function drive() {
            echo "Car class drive method...<br/>";
        }
        
    }
    
    $car = new Car();
    $car->name = "Mercedes benz";
    
    // calling child class method
    $car->drive();
    
?>

Output:

Fatal error: Cannot override final method Vehicle::drive()

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.