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

Thursday 8 October 2020

What is destructor? explain with example in php

 DESTRUCTOR

  • A destructor is called when the object is destroyed.
  • A destructor is a special method called automatically during the destruction of an object. Actions executed in the destructor include the following
    • Recovering the heap space allocated during the lifetime of an object
    • Closing file or database connections
    • Releasing network resources
    • Releasing resource locks
    • Other housekeeping tasks

Example of Constructor and Destructor:
<?php
class dclass
{
    public $name = "Youtube with Avadh Tutor";    
    public function __construct($name)
    {
        echo "<font color=blue>By default Constructor</font>";    
        $this->name = $name;
    }
    
    public function __destruct()
    {
        echo "<font color=orange>Class with destructor Call </font>";
//$this->name = $name; /*error*/
    }
}

$d = new dclass("Argument");
echo "<br><br>Name of the Channel: " . $d->name;
/* destruct call after object destroy*/
?>