Class Constructors and Destructors

A constructor is a special method defined for a class that is run automatically when an object is instantiated for the class. Similarly a destructor is a special method that is run automatically when the object is destroyed. These methods use the special names __construct and __destruct. Old versions of PHP used the class name as the method name for the constructor and didn't support destructors.

class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
function __destruct() {
print "Destroying BaseClass\n";
}
}
 
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}

In this example creating an object from BaseClass will result in the constructor running (and hence in this example the message indicating that will be displayed). When that object is eventually destroyed - either by it moving out of scope or being explicitly destroyed - then the destructor will run.

$obj = new BaseClass();

Where a class is defined that extends the functionality of another class the way SubClass extends our BaseClass in the above example then the BaseClass constructor will be inherited by the SubClass as long as the new class does not define a constructor of its own. Where the new class does define its own constructor then that constructor will be run when an object is created and the constructor on the BaseClass will not be run unless it is explicitly called (as is the case in the above example). As our SubClass example does not define its own destructor method it will inherit the one from BaseClass.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate