NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP 5 Throwing Exceptions in Constructors

Adam Maccabee Trachtenberg adam at trachtenberg.com
Wed Feb 9 17:39:35 EST 2005


On Wed, 9 Feb 2005, Hans Zaunere wrote:

> > PHP is not Java. :)
>
> Riiiight... but it does have the same behavior :)

It has similar behavior, but is just different enough to slip you
up. For instance, there's no concept of Checked vs. Unchecked
exceptions in PHP.

> But what if a class should still be instantiated, even if some of
> the arguments are incorrect, or subsequent parts fail for some
> reason?  True, this validation could be done outside of the
> constructor, even in a totally different class that the constructor
> instantiates itself, but this still would prevent the instantiation
> of the original class.

This is a ZE2 limitation. The only way to signal failure from a
constructor is via an exception. Even extensions that never throw
exceptions throw them in the constructor.

If you're concerned a non-essential portion can fail, you can either:

a) Don't throw an exception in that instance, return the object, and
provide developers with a way to check status.

b) Don't place that functionality in the constructor, and provide a
method to update the object with the additional data.

-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
Automatic Email Organization without missing anything!