Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

PHP - Constructors and Destructors

From Wiki
Jump to: navigation, search
Article Metadata
Article
Created: Maveric (28 Jun 2011)
Last edited: hamishwillee (31 Jul 2012)

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

This page was last modified on 31 July 2012, at 07:30.
153 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×