Wednesday, 14 October 2020

What is Parameterized constructor in PHP? Explain with Example

Parameterized constructor 
  • Parameterized constructor is a constructor that accepts parameter and is normally used to initialize member variables at the time of object creation.
  • The constructor of the class accepts arguments or parameters
Example:

<form action="" method="post">
Enter Code:<input type="text" name="code" value="" /><br />
Enter Name:<input type="text" name="name" value="">
<br />
<input type="submit" name="sb" value="Click" />
</form>

<?php
//Paramiterrized Constructor
$code = $_POST['code'];
$name = $_POST['name'];
class Employee
{
var $empcode;
var $empname;
function Employee($code,$name)
/*class name and function name are same but different variable passed as known as a parameterized constructor*/
{
$this->empcode = $code;
$this->empname = $name;
}
function display()
{
echo " <h1><br>";
echo "<br> Employee Code : " . $this->empcode;
echo "<br> Employee Name : " . $this->empname;
echo "</h1>";
}
};
$object = new Employee($code,$name);

$object -> display();
?>

No comments:

Post a Comment