Constructors and Destructors - Why?
Moderator: General Moderators
- trukfixer
- Forum Contributor
- Posts: 174
- Joined: Fri May 21, 2004 3:14 pm
- Location: Miami, Florida, USA
Constructors and Destructors - Why?
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!
Bri!
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.
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
the use of constructors is invaluable for setting the environment for that particular object.
A quick and dirty example (php5):
Another example could be you want to list order of methods to be called transparantly without having to manually call them
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.
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');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.
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
now, in most languages, you can't initialize a property in the class definition, but you do initialize them in the constructor. e.g.:And that's all fine and dandy for most. But what if you need to run code or create an object in this property?The above example doesn't fly:This is where a constructor becomes very useful.The same goes for wanting to initialize based on use input:
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.
Code: Select all
<?php
class a
{
public $foo;
public function __contruct()
{
$this->foo = '';
}
}
?>as opposed to<?php
class b
{
public $foo = '';
}
?>Code: Select all
<?php
class c
{
private $foo = new a();
}
?>Code: Select all
Parse error: syntax error, unexpected T_NEW in Command line code on line 5Code: Select all
<?php
class c
{
private $foo;
public function __construct()
{
$this->foo = new a();
}
}
?>Code: Select all
<?php
class c
{
private $foo;
public function __construct($fooData)
{
$this->foo = $fooData;
}
}
?>-
alex.barylski
- DevNet Evangelist
- Posts: 6267
- Joined: Tue Dec 21, 2004 5:00 pm
- Location: Winnipeg
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...
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
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!!!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
- AKA Panama Jack
- Forum Regular
- Posts: 878
- Joined: Mon Nov 14, 2005 4:21 pm
Actually no reason to use __construct(...)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');
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');- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
In terms of backward compatability, your right, it obviously isn't good to use __construct (php5 only)..AKA Panama Jack wrote:Actually no reason to use __construct(...)
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
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Constructors and Destructors - Why?
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.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...
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
Code: Select all
$catinthehat->addThing(new Thing('one'));
$catinthehat->addThing(new Thing('two'));(#10850)
- AKA Panama Jack
- Forum Regular
- Posts: 878
- Joined: Mon Nov 14, 2005 4:21 pm
That would be very silly.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.
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.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
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.
(#10850)
- Maugrim_The_Reaper
- DevNet Master
- Posts: 2704
- Joined: Tue Nov 02, 2004 5:43 am
- Location: Ireland
I'm sure I don't have to mention my enourmous support and embrace of standards as a general rule.feyd wrote:Run something claiming compatibility with strict mode on, it's fun getting 500 "var deprecated" warnings. But I digress.
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.