Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is overloading and overriding in php?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.14k
    Comment on it

    Overriding:


    When we inherit a class into another class and provide the definition for one of the function of parent class  inside the child class, then this function is overridden and this process is known as function overridding. Overriding is the runtime polymorphism.

    It is the process of defining a method  in a child class with the same declaration as in the parent class but this method will perform different task. Overriding is removing  its current statements and replacing them with new statements. It means calling of child function instead of parent function, both classes have same function name.

     

     

    Example of Overriding: 

    public class Forestanimal {
          public function catSpeak() {
              echo "Cat Speaking";
          }
        
    
    
       // This is overloading the method catSpeak.
          public function catspeak($sound) {
            echo  $sound;
          }
        }

     

     

     

    Overloading:


    When we have more than one function of  same name and return type but having different arguments is called function overloading. Overloading is defining more than one function with the same name but with different signatures. In overloading inheritance is not necessary. Functions having same name  can have different datatypes and access specifiers.

    It is the ability to create multiple functions with the same name but with different implementations. Overloading is the concept of compiletime polymorphism.

     


    Example of Overloading:  

      public class Forestanimal {
          public function catSpeak() {
              echo "Cat Speaking";
          }
        }
    
    
    class Cat extends Forestanimal {
     
      public function catspeak() {
      echo "Function overridding";
      }
    }

     


    We can also do overloading with magic methods:
    __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo()

     

     


    Comment:   The first method "catSpeak()" is overriding the method catSpeak from Forestanimal, and the second "catSpeak($sound)" is overloading the method catSpeak.

     

 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: