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.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.