PHP Constructor And Destructor

PHP Constructor And Destructor



A PHP constructor and a destructor are special functions that are automatically called when an object is created and destroyed.

PHP Constructors are special member functions for initializing variables on the newly created object instances from a class.

When creating a new object, it's useful to set up certain aspects of the object at the same time. For example, you might want to set some properties to initial values, fetch some information from a database to populate the object, or register the object in some way.

Similarly, when it's time for an object to disappear, it can be useful to tidy up aspects of the object, such as closing any related open files and database connections, or unsetting other related objects.

An object's constructor method is called just after the object is created, and its destructor method is called just before the object is freed from memory.

PHP Constructor Types:
1. Default PHP Constructor:
-Default PHP constructor has no parameter or arguments, but the values to the default constructor can be passed dynamically
-We can define constructor by using
 function __construct().

Example:
<?php
class Filmyzilla
{
 function __construct()
 {
  echo "I am PHP Default Constructor";
 }
}
$ob=new Filmyzilla();
?>
Output: I am PHP Default Constructor
2. Parametrized PHP constructor:
-Parametrized PHP constructor takes the parameters and also you can pass different values to the data members.
-The parameterized constructor is a constructor that accepts parameters and is normally used to initialize member variables at the time of object creation.

Example:
<?php
class Filmyzilla
{
 function __construct($n1,$n2)
 {
  $this->n1=$n1;
  $this->n2=$n2;
 }
 function Add()
 {
  echo "Addition",$this->n1+$this->n2;
 }
}
$ob=new Filmyzilla(1,2);
$ob->Add();
?>
Output: Addition 3

PHP Destructor:
PHP Destructor can't accept arguments. An object's destructor is called just before the object is deleted. This can happen because all references to it have disappeared or when the script exits, either naturally or because of an error of some sort. In each case, the object gets a chance to clean itself up via its destructor before it vanishes.

Example:
<?php
class Filmyzilla
{
 function __construct($n1,$n2)
 {
  $this->n1=$n1;
  $this->n2=$n2;
 }
 function __destruct()
 {
  echo "<br>I am PHP Destructor|| Destroyed";
 }
 function Add()
 {
  echo "Addition",$this->n1+$this->n2;
 }

}
$ob=new Filmyzilla(1,2);
$ob->Add();
?>
Output: Addition3
I am PHP Destructor|| Destroyed
MSBTE I Scheme Questions: (4Marks)
Q. Explain PHP Constructor and Destructor.
Q.Describe Default Constructor with suitable Example.
Q.Describe Paramertized Constructor with suitable Example.

Comments