PHP Constructor and Destructor
PHP - The __construct Function
The __construct()
keyword is used to create a constructor within a class.
A constructor nothing but a normal php function with some special features.
The main difference between a normal function and constructor is:
- When you create an object from a class, PHP will automatically call the
__construct()
function you defined. - This function's name is construct by a pair of underscores (__)!. You cannot change the constructor name.
It will be very useful when you want to initialize default value to class member before execute or call any other methods.
Note:- A constructor can have function overloading like other normal functions.
Example 1:- A basic or default constructor.
Output :-
Note: In the above example, we did not call the __constructor
function and its execute automatically.
Example 2 : Creating a constructor with parameters and used to set default values to properties.
a = $a;
$this->b = $b;
}
// This is a normal to set "a" and "b" values
// This function will execute after calling manually.
function setAB($a, $b) {
$this->a = $a;
$this->b = $b;
}
function do_Addition() {
$c = $this->a + $this->b;
echo "
Addition is : " . $c;
}
function do_Subtraction() {
$c = $this->a - $this->b;
echo "
Subtraction is : " . $c;
}
}
$cc = new Calculator(25, 15);
$cc->do_Addition();
$cc->do_Subtraction();
$cc->setAB(1 , 2);
$cc->do_Addition();
$cc->do_Subtraction();
?>
Output :-
Subtraction is : 10
Addition is : 3
Subtraction is : -1
Related Links
PHP __destruct Function
When an object is destroyed or when a script is terminated or quit, a destructor is invoked to destroy it.
This function will be called automatically at the end of the script if you add a function named __destruct()
.
There are two underscores(__) at the beginning of the destruct function!
Example :- Here's an example script that includes two functions : one executed automatically when an object is created from a class, and one called automatically at the end :
name = $name;
echo "
" . $this->name ." is created!";
}
function __destruct() {
echo "
" . $this->name ." is destroyed!";
}
}
$apple = new Fruit("Apple");
$banana = new Fruit("Banana");
?>
Output :-
Banana is created!
Banana is destroyed!
Apple is destroyed!
Tip : Constructors and destructors are particularly beneficial since they assist reduce the amount of code.
Related Links