[Tutor] constructors

Erik Price erikprice@mac.com
Thu, 11 Apr 2002 07:42:54 -0400


On Thursday, April 11, 2002, at 12:23  AM, Karthik Gurumurthy wrote:

>> So, if I had an class with a method that did a database access, then 
>> the
>> constructor could do something like initialize the variables used in 
>> the
>> class, and create a database connection.  If the database connection
>> fails, then the constructor could return false, which would fail the
>> creation of the object instance, so that we don't waste our time
>> accessing the methods of the class since we already know we couldn't
>> establish a database connection.
>
>> ...does this sound right?
>
> Yes Perfect!. you have picked up a nice example.
> Normally constructors do not have a return value. Instead they throw
> exceptions.
>
> So if you have a DatabaseManager class which control access to the 
> database,
> you w'd probabyl try
> initializing the connections in the constructor. If it fails, you w'd
> probably signal the same by throwing
> an exception. So the client w'd'nt be able to use that object.

I see.  The use of constructors is becoming much more concrete to me.  
Thank you Karthik.  But as always, this conversation now brings up yet 
another question! :)  It's a simple one though.  I'm just wondering 
whether it would be better to throw an exception from within the class 
method (or constructor), or whether it would be better to simply do an 
"if" test and have it return false -- and then throw an exception from 
the calling script itself, if the "new object" calling fails.  I would 
have leaned toward the former -- returning false from a failed method, 
and then throwing up an error message from the calling script because 
the creation of a new object instance failed, but that's because I'm not 
totally clear on exceptions yet (they don't have them in PHP AFAIK, I 
just write my own error-handling code).


Erik