OOP - Object lifetime : Instance of a class, constructors, destructors

Posted under » Methodology on 04 November 2012

To use the variables and functions defined by a class, you create an instance of the class, which is referred to as an object. This creates an object called $val.

In Php
$val = new Pos_Validator();
In Python
val = Pos_Validator()

To construct is to init the object with some values.

In Python

def __init__(self):
    self.data = []

In Php using new unified constructors

class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";

class SubClass extends BaseClass {
   function __construct() {
       print "In SubClass constructor\n";

$obj = new BaseClass();
$obj = new SubClass();

The destructor method will be called as soon as there are no other references to a particular object to save memory etc., or in any order during the shutdown sequence.

    class Person {
        // first name of person
        private $fname;
        // last name of person
        private $lname;
        // Constructor
        public function __construct($fname, $lname) {
            echo "Initialising the object...
"; $this->fname = $fname; $this->lname = $lname; } // Destructor public function __destruct(){ // clean up resources or do something else echo "Destroying Object..."; } // public method to show name public function showName() { echo "My name is: " . $this->fname . " " . $this->lname . "
"; } } // creating class object $harry = new Person("Harry", "LKY"); $harry->showName();

As we can see in the output above, as the PHP program ends, just before it PHP initiates the release of the object created, and hence the destructor method is called.

The destructor method cannot accept any argument and is called just before the object is deleted, which happens either when no reference exist for an object or when the PHP script finishes its execution.

NOTE: If you see a PHP class with a function having same name as the name of the class, then that function will act as the constructor.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data