Lesson 18 - Inheritance and Methods in PHP

Inheritance allows classes to pass their properties and methods to other classes. Let us analyze the following PHP code to further understand this:


<?php 
//parent class
class main{
     public function welcome(){
             echo "Welcome!!! have a nice day";
          }
     public function goodbye(){
            echo "Goodbye everyone!! good luck";
          }
}
//child class
class child extends main{
         
}
?>

The previous PHP code has  a parent class named "main" as well as a child class named "child". To create a child class the keyword "class" is followed by the name of the child class and the keyword "extends", finally the name of the parent class is typed, in this case "main".

Child classes can use the methods of the parent class. Let us instantiate an object using the child class and try to call the methods of the parent class:

//instantiating object 
$object=new child();
echo $object->welcome();
echo "<br/>";      //line break using HTML
echo $object->goodbye(); 

The previous PHP code instantiates an object by declaring the variable "$object" followed by the keyword "new" and the name of the child class. Later, the methods of the parent class are called by using  the variable "$object" followed by the operator "->" and the name of the method. 

After executing the previous PHP script the outcome looks as follows:

Welcome!!! have a nice day
Goodbye everyone!! good luck

As a conclusion we can state that child classes can use methods from parent classes. The objects instantiated from child classes can use the methods of the parent class as well.
 

No comments:

Post a Comment