PHP OOPs - Method Overriding

What is Method Overriding in php?

If both parent and child classes have same function name with number of arguments, then it is called Method Overriding in php object oriented programming.

  • Parent methods can be overridden by method of child class.
  • The constructor __construct() in the child class will override the constructor __construct() of the parent class.

PHP Example :

 

<?php
//code by aryatechno!
class Aryatechno{
   public function __construct()
   {
       echo "Parent constructor is overriden by constructor of child class \n" ;
   }
   public function courselist(){
      echo "This method is overriden by method of child class \n" ;
      echo "Aryatechno provides courses like : PHP,JAVA,HTML. \n" ;
   }
   
}
class Courses extends Aryatechno{

   public function __construct()
   {
       echo "Child constructor overrides constructor of parent class \n" ;
   }
   
   public function courselist(){
      echo "This method will override method of parent class \n" ;
      echo "Aryatechno provides Database courses like : MYSQL,Oracle,MSSQL. \n" ;
   }
   
}
$obj=new Courses();
$obj->courselist();

?>

Output:

Child constructor overrides constructor of parent class
This method will override method of parent class
Aryatechno provides Database courses like : MYSQL,Oracle,MSSQL.

PHP - The final Keyword

  • The final keyword can be used to prevent class inheritance.
  • The final keyword can be used to prevent method overriding.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

51176