PHP - Constructors and Destructors
Article Metadata
This article explains PHP constructor and destructor concept.
Introduction
When in PHP we want to create a constructor, the naming convention is to add two underscores before the name of the function. Basically this would be like a normal function, with the difference that the constructor function gets called first before anything else happens, and this would take place every time an object is created out from the base class.
The point of use would be e.g. to initialize some variables or pre-calling something before the rest of the object gets used. As the constructor is a regular function, also parameters can be passed.
For any constructor function, there is also it's counterpart; the destructor. It is used for cleanup and it will be called just when the script is about to end and all objects will be deleted. Some use this part of the life-cycle also for executing something final other operations on the program.
Implementation with example code
Create new class and populate it with a constructor.
<?php
class Marko{
public function __construct(){
echo "Not so fast, get some coffee!";
}
}
?>
Create new object, during which the constructor gets called from within.
<?php
//...
$someObject = new Marko();
//...
?>
We could now e.g. add a parameter to the constructor, to pass data and add the destructor too.
The object creation could be e.g.
$someObject = new Marko("(don't forget to mix it with some sugar and milk too)");
For the destructor we would add:
public function __destruct(){
echo "Destruction complete. Thank you. And good bye!";
}
Both constructor and destructor implemented:
<?php
class Marko{
public function __construct($x){
echo "Not so fast, get some coffee $x !";
}
public function __destruct() {
echo "Destruction complete. Thank you. And good bye!";
}
}
?>
For the code above, if we would now create an object, we would get displayed:
/*
Not so fast, get some coffee (don't forget to mix it with some sugar and milk too) !
Destruction complete. Thank you. And good bye!
*/Tested with
PHP 5.x


(no comments yet)