NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP 5 Throwing Exceptions in Constructors

Hans Zaunere lists at zaunere.com
Wed Feb 9 15:01:31 EST 2005


Hi all,

All PHP 5 code examples I've seen show try/catch pairs like this:

try {
	$obj = new MyClass;
	$obj->DoSomething();
} catch( Exception $e ) {
	echo $e->getMessage();
}

I am the only one in thinking that these examples are incorrect 99% of the time?  Based on other languages, like Java, exceptions should very very rarely be thrown from a class' constructor.  The simple reason, as in PHP 5, is that the object never gets created if an exception is thrown in the constructor.

Is there something particular to PHP 5 that I'm missing?  While it could be considered pedantic, PHP 5 code examples should be as:

$obj = new MyClass;

try {
	$obj->DoSomething();
} catch( Exception $e ) {
	echo $e->getMessage();
}


In fact, in PHP 5 I cannot find anyway to determine the "return" value of the new operator.  This leads me to believe that PHP 5's concept of proper OO is to always assume the object is created successfully, unless a catastrophic event happens, in which case an exception is thrown, and the object isn't created at all.  This of course makes sense, but then I'm confused as to why the code samples all seem a bit incorrect.

Interested in hearing thoughts on this...


---
Hans Zaunere
President, Founder
New York PHP
http://www.nyphp.org






More information about the talk mailing list