Constructor function basics

Submitted on Fri, 08/14/2020 - 16:41

Code:

<?php

class parentClass 

{

function __construct() 

{
print "<p>I am a responsible parent.</p>";
}

}

class childClass extends parentClass 

{

function __construct()

{
    
// This class has its own constructor function but it also calls the parent constructor.
parent::__construct();        
print "<p>I am a thoughtful child.</p>";
}

}

class wildchildClass extends parentClass 

{

function __construct()

{

// This class has its own constructor function. 
// Hence this function will be called when the object of this class is initiated.

print "<p>I am wild child.</p>";


}

}

class dumbchildClass extends parentClass 

{
// Doesnt have its own constructor function.
// Hence when object of this class is initiated, constructor of parent class is called by default.

}

new childClass();

new wildchildClass();

new dumbchildClass();

?>

 

Expected Output:

I am a responsible parent.

I am a thoughtful child.

I am wild child.

I am a responsible parent.