NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP 5 Throwing Exceptions in Constructors

Adam Maccabee Trachtenberg adam at trachtenberg.com
Wed Feb 9 15:27:18 EST 2005


On Wed, 9 Feb 2005, Hans Zaunere wrote:

> 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();
> }
>

This is correct.

> 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.

PHP is not Java. :)

> 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();
> }
>

This is incorrect.

> 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.

In PHP 5, the way to signal failure in a constructor is to throw an
exception. There is no other way to communicate errors. As "new" will
not return "false".

Exceptions do not have to occur due to catastrophic failures, such as
lack of memory. This can also occur due to bad input parameters. For
example, passing the wrong number of parameters, or if you try to
create a DOMElement with an illegal XML element name.

See pages 188-9 of "Upgrading to PHP 5" by, um, I forget. :)

-adam


-- 
adam at trachtenberg.com | http://www.trachtenberg.com author of
o'reilly's "upgrading to php 5" and "php cookbook" avoid the holiday
rush, buy your copies today!



More information about the talk mailing list