[nycphp-talk] PHP 5 Throwing Exceptions in Constructors
Hans Zaunere
lists at zaunere.com
Mon Feb 14 13:00:47 EST 2005
> > I was dealing with this exact same dilemma on a project I'm currently
> > coding.
> > We ending up going with Adam's option B: move the code which can fail
> > to outside the constructor.
> >
> > In the original design the you could create an object where the
> > constructor could read some information from a database.
> >
> > In the final design, we moved the database code to a new load()
> > function that executes the actual database call. This does add an
> > additional step, but having the constructor throw an execution just
> > messes things up.
>
> This is a best practice in many OO languages (for instance c++)
Yeah, I in fact have an Init() method just for these reasons.
The issue really wasn't even about a constructor. It boiled down to the fact that throwing an exception is just too "strong" for what I wanted to do, ie, let the object be created regardless.
Even after moving the throw out of __construct(), if __construct() called some other object or method that threw an exception, it was killed. Sure, I could have added a bunch of try/catch pairs, but I started to feel I was removing encapsulation. I ended up having these potential problem areas simply set properties, which can then be accessed later.
I guess the takeaway here is that if you have simple base classes that can succeed to different degrees or not, it's better to not have them throw exceptions unless you want to ensure a major change in program flow (thus, an exception :)
---
Hans Zaunere
President, Founder
New York PHP
http://www.nyphp.org
AMP Technology
Supporting Apache, MySQL and PHP
More information about the talk
mailing list