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();
?>

How to Create Simple Class using PHP

What is Class in PHP

  • class is a container that can contain variables, constructors, functions etc.
  • This is a programmer-defined data type, which includes local functions as well as local data.
  • A class is a self-contained, independent collection of variables and functions which work together to perform one or more specific tasks, while objects are individual instances of a class.

Syntax:

class classname
{
variables
function functionname
{
--
}

}

class object
calling function
display function

Example: 

<?php
class student
{
//var $rollno;
//var $name;
function get()
{
$this->rollno = 10;
$this->name = 'raj';
}
function display()
{
echo "<pre><br>Roll No : " . $this->rollno;
echo "<br>Name : " . $this->name;
}
};
$obj = new student();
$obj->get();
$obj->display();
?>


Learn all the programming inside youtube.com/avadhtutor