Page 1 of 2
Constructors and Destructors - Why?
Posted: Sun Feb 26, 2006 8:33 pm
by trukfixer
OK. here's another thing Ive noticed in *some* classes I have looked at - Some have "constructors" and "destructor" functions , and in trying to understand them I end up totally lost - What is the purpose? Ive tried using the class with the constructor comkmented out, and everything worked just fine, (It looked to me, like it was just a way to abstract and "declare" a function or object if one hadnt already been instantiated, but then again, maybe I was thinking the wrong way - Why should these be used? what are the recommendations? Why is it that code seems to work equally well with or without the constructors ? (again, this is me, trying to rationalize what looks at first glance, top be just additional code bloat.) Ive never used either, and really dont see the point in creating them .. What's the point? What's the value ? Even though Ive read about this at php.net , I still just dont "get" it...
Bri!
Posted: Sun Feb 26, 2006 9:04 pm
by josh
Constructers are just methods that get called when the object is instantiated, destructures are called when the object gets destroyed. The only reason for an empty constructer would be that when object a extends object b PHP tries to call a constructer on A, if its not found it looks to B. The placeholder on A would prevent the constructer of B from being called when A is instantiated.
Posted: Sun Feb 26, 2006 9:17 pm
by John Cartwright
the use of constructors is invaluable for setting the environment for that particular object.
A quick and dirty example (php5):
Code: Select all
class MysqlConnection
{
private $link;
function __construct($host, $dbname, $user, $pass) {
$this->link = mysql_connect( ... );
}
}
$db = new MysqlConnect('localhost', 'db1', 'user', 'pass');
Another example could be you want to list order of methods to be called transparantly without having to manually call them
Code: Select all
class testClass
{
function __construct() {
$this->runParam1();
$this->runParam2();
}
}
Basically it comes down to when instantiated the class, you are able to pass arguments to the function, as well as automate certain methods of the class
Same principle for a destructor.. when your page is finished the destructor acts as a "cleanup" to allow a final method to be called to finish up anything the class may need to do.
Posted: Sun Feb 26, 2006 10:27 pm
by feyd
now, in most languages, you can't initialize a property in the class definition, but you do initialize them in the constructor. e.g.:
Code: Select all
<?php
class a
{
public $foo;
public function __contruct()
{
$this->foo = '';
}
}
?>as opposed to<?php
class b
{
public $foo = '';
}
?>
And that's all fine and dandy for most. But what if you need to run code or create an object in this property?
Code: Select all
<?php
class c
{
private $foo = new a();
}
?>
The above example doesn't fly:
Code: Select all
Parse error: syntax error, unexpected T_NEW in Command line code on line 5
This is where a constructor becomes very useful.
Code: Select all
<?php
class c
{
private $foo;
public function __construct()
{
$this->foo = new a();
}
}
?>
The same goes for wanting to initialize based on use input:
Code: Select all
<?php
class c
{
private $foo;
public function __construct($fooData)
{
$this->foo = $fooData;
}
}
?>
It is recommended to always have a constructor if you have any properties in the object. I extend that by suggesting that you should always have a constructor, properties or not. It's personal preference there, and may have a
slight hit on performance if you don't have properties, but I feel it is best to explicitly show that you don't have a constructor hidden away somewhere, maybe in a parent object.
Posted: Sun Feb 26, 2006 11:55 pm
by alex.barylski
Just wanna add my 2 cents:
Like already noted, constructors are called automatically whenever an object is created using
new. They are typically used to initialize data members, allocate resources, etc...
Code: Select all
$myClass = new MyClass(); // Constructor called
$myClass->MyClass(); // No need to explicitly call constructor - done already!!!
Constructors/Destructors are special member functions, in that they are never called directly - or typically shouldn't be! They also DO NOT return values. Destructors do not take parameters and therefore cannot be overloaded.
The reason your object still worked despite you NOT defining CTor (constructor) is that most if not all, languages that support OOP use a default constructor when one is not provided, which basically does nothing.
I'm willing to bet PHP does the same thing, so if you did declare an empty CTor() other than parsing time, there probably isn't any hit in performance. Remember that a default constructor is one with no parameters or return values, so if it does nothing and therefore no prologue and epilogue is ever executed so there is no waste - at least I would imagine so.
So like Feyd said, it's a good idea to supply a CTor just for the sake of having it visible and in the future you can implement it if needed.
Basically Ctor/DTor were introduced to automate initialization/cleanup in objects and are especially handy in languages like C++ where garbage cleanup isn't done for you.
Because of the GC in PHP destructors aren't really as handy or required - I assume thats why they skipped destructors (I think 5 has dtor support).
Cheers

Posted: Mon Feb 27, 2006 12:00 am
by feyd
psst, destructors can be overloaded.
Posted: Mon Feb 27, 2006 12:38 am
by AKA Panama Jack
Jcart wrote:the use of constructors is invaluable for setting the environment for that particular object.
A quick and dirty example (php5):
Code: Select all
class MysqlConnection
{
private $link;
function __construct($host, $dbname, $user, $pass) {
$this->link = mysql_connect( ... );
}
}
$db = new MysqlConnect('localhost', 'db1', 'user', 'pass');
Actually no reason to use __construct(...)
You can use this instead...
Code: Select all
class MysqlConnection
{
private $link;
function MysqlConnection($host, $dbname, $user, $pass) {
$this->link = mysql_connect( ... );
}
}
$db = new MysqlConnection('localhost', 'db1', 'user', 'pass');
Once the object is created it will call the function of the same name. If you want to maintain backward compatability with PHP4 you will not use the __construct method but name the function the same as the class name.
Posted: Mon Feb 27, 2006 12:59 am
by feyd
__construct() and a function named after the class name are roughly aliases of each other. Although having both in a class is silly, and will fire a strict warning.
Posted: Mon Feb 27, 2006 1:15 am
by John Cartwright
AKA Panama Jack wrote:Actually no reason to use __construct(...)
In terms of backward compatability, your right, it obviously isn't good to use __construct (php5 only)..
although I am picky about my class names, so having a constructor method name the same as a descriptive class name doesn't make much sense to me
Re: Constructors and Destructors - Why?
Posted: Mon Feb 27, 2006 1:53 am
by Christopher
trukfixer wrote:OK. here's another thing Ive noticed in *some* classes I have looked at - Some have "constructors" and "destructor" functions , and in trying to understand them I end up totally lost - What is the purpose? Ive tried using the class with the constructor comkmented out, and everything worked just fine, (It looked to me, like it was just a way to abstract and "declare" a function or object if one hadnt already been instantiated, but then again, maybe I was thinking the wrong way - Why should these be used? what are the recommendations? Why is it that code seems to work equally well with or without the constructors ? (again, this is me, trying to rationalize what looks at first glance, top be just additional code bloat.) Ive never used either, and really dont see the point in creating them .. What's the point? What's the value ? Even though Ive read about this at php.net , I still just dont "get" it...
It is interesting that you would ask this question after asking about accessors (getters/setters). As people have noted, the contructor is a function that is called when the object is created. Likewise a destructor is used when it is freed. Destructors are not used very often and you will probably do a lot of programming before you might need them. But constructors are very important and get to the heart of OO in some ways.
Think of the constructor as a setter function that you can use when you create an object. The point is to have a usable object upon creation -- rather than having to use accessors. Unlike procedural programming where you have functions and run data through them, in OOP you start with the data and then apply what are essentially namespaced functions on the data. So it is important that the object is initialized. Think of objects as being living data -- as opposed to the inanimate data of procedural programming.
Finally, because constructors act as setters they are often used to make using objects easier (so you do more of it

), for example:
Code: Select all
$catinthehat->addThing(new Thing('one'));
$catinthehat->addThing(new Thing('two'));
Posted: Mon Feb 27, 2006 2:23 am
by AKA Panama Jack
feyd wrote:__construct() and a function named after the class name are roughly aliases of each other. Although having both in a class is silly, and will fire a strict warning.
That would be very silly.
I make the function name the same as the class name because I need backward compatability with PHP4. I use it for the language support for the different classes in the game I write. When the object is created it checks to see what language the player is using and populates the language variables used in the class with their language data. It makes things so much easier and no need to have seperate language files because it is all self contained in the class.
Posted: Mon Feb 27, 2006 2:31 am
by feyd
Run something claiming compatibility with strict mode on, it's fun getting 500 "var deprecated" warnings. But I digress.
Posted: Mon Feb 27, 2006 2:45 am
by Christopher
For me, the advantage of "__constuct()" rather than "ClassName()" is in refactoring. Often when you create a class you get the name a little wrong. Using "__constuct()" simplifies refactoring because you don't have to rename the class and the constructor. It is one less mistake to make when renaming a class. I suppose down the road it will help tools like IDEs and class generators as well.
Posted: Mon Feb 27, 2006 3:03 am
by Maugrim_The_Reaper
Some of us still need to maintain PHP4 backwards compatibility...unfortunately.
Posted: Mon Feb 27, 2006 8:18 am
by Roja
feyd wrote:Run something claiming compatibility with strict mode on, it's fun getting 500 "var deprecated" warnings. But I digress.
I'm sure I don't have to mention my enourmous support and embrace of standards as a general rule.
However, in this case, even the PHP team recognized that setting var as deprecated was beyond evil and inaccurate. PHP6 will not do so.
I just worked on porting d11's css graphing class, and that was one of the changes I made - setting a __construct to the class name. Doesn't bother me in the least, I really can't see any substantial difference logically. It acts the same, it just has a different name.
But honestly, I think thats a bit off-topic. Its still a constructor. The question was what the purpose of constructors is, not how they should be implemented on php4 or php5.
I'll throw in my cheap-seats answer and say "So that you can perform actions upon creation". Whether thats setting up a needed array, or creating other objects, it's a special sequence that you occassionally need/want.
Frequency of use/need by person will vary based on your embrace of OOP, I guess.