Wednesday, 30 September 2020

What is Constructor? Explain with Example

What is Constructor:

  • is a member function of a class which initializes objects of a class
  • If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
  • Class name and method name are same that called as a constructor

Example: 

<?php
class Employee
{
var $empcode;
var $empname;
function Employee()
//not passed as a parameter
{
$this->empcode = 100;
$this->empname='avadh tutor';
}
function display()
{
echo "<h1><br>";
echo "<br>Emp Code = " . $this->empcode;
echo "<br>Emp Name = " . $this->empname;
echo "</h1>";
}
};
$instance = new Employee(); // Constructor automatically call
$instance -> display();
?>

No comments:

Post a Comment