Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make a class/method abstract in php

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 147
    Comment on it

    Here we will learn about the abstract classes and methods. When we define a classes as an abstract then we have to follow the below rules:

    1- We can not create an object of this abstract class.
    2- The class becomes abstract if the class contains at least one abstract method.
    3- Abstract methods are only declared and not defined.
    4- All abstract methods declared in the parent class must be defined by the child class.
    5- And the visibility of the abstract method must be equal or less than that in parent class when
    defined by the child class.


    Example:

    abstract class MainClass
    {
    
        abstract protected function xyz(); //This class must be defined in the child class when extended    
        abstract protected function abc($g); //This class must be defined in the child class when extended
    
        // This method is the common method for parent and child
        public function Display()
        {
          print  $this->xyz();
        }
    }
    
    class subClass extends MainClass
    {
        protected function xyz() {
            return "abstract method xyz() is mandatory to define in the child class as it is abstract method/ class";
        }
    
        // the visibility of abc method is less restricted than in the parent class
        public function abc($g) {
            echo "{$g} this method is also abstract method ";
        }
    }
    
    
    $sbclass = new subClass();
    $sbclass->Display();
    $sbclass->abc('<br> Hello there') ;
    
    OUTPUT:
    
    abstract method xyz() is mandatory to define in the child class as it is abstract method/class
    Hello there.. this method is also abstract method
    

 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: