Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Inheritance in PHP

    • 0
    • 1
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 903
    Comment on it

    Hello Readers ,

    Here's the explanation of concept of Inheritance in PHP.

    What is inheritance?

    Inheritance is nothing but a design principle in oop. By implementing inheritance we can inherit(or get) all properties and methods of one class to another class.The class who inherit feature of another class known as child class.The class which is being inherited is know as parent class.

    Body of Single level Inheritance.

    class grandParent
    {
       //Body of your class
    }
    
    class parent extends grandParent
    {
       //Body Of your class
    }
    

    Body of Multilevel Inheritance.

    class grandParent
    {
       //Body of your class
     }
    
    class parent extends grandParent
    {
       //Body Of your class
      }
    
    class child extends parent
    {
      //Body of your class
    }
    

    Example of Single level Inheritance.

    Creating a Class called Books which will have it's own variables and function.

    <?php
    
    class  Books{
    
        /* Member variables */
    
        var $price;
        var $title;
    
        /* Member functions */
    
        function setPrice($par){
           $this->price = $par;
        }
    
        function getPrice(){
           echo $this->price ."<br/>";
        }
    
        function setTitle($par){
           $this->title = $par;
        }
    
        function getTitle(){
           echo $this->title ." <br/>";
        }
    }
    
    ?>
    

    Now creating a Child Class called Novel which will extend the Parent Class called Books.

    <?php 
    
    class Novel extends Books{
    
       var publisher;
    
       function setPublisher($par){
         $this->publisher = $par;
       }
    
       function getPublisher(){
         echo $this->publisher. "<br />";
       }
    }
    
    ?>
    

    Here we see Class Novel has extended the Class Books which means Class Novel now can excess all the variables and functions that Class Books has used.

    This is the simple and very useful concept of Inheritance in PHP.

    Good Luck!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: