Re: Raising errors inside a constructor

From: Date: Mon, 16 Aug 2004 11:47:09 +0000
Subject: Re: Raising errors inside a constructor
References: 1 2 3 4  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-32705@lists.php.net to get a copy of this message
Alan Knowles wrote:
Why a such ugly thing : $foo =& Foo::construct($options); if (PEAR::isError($foo)) { ... } when you could do : $foo = new Foo($options); if ($foo->hasError()) { ... } ?
a) will probably throw a "no such method error" at some point,
Well, this is no big deal. You got to know which of the classes you use are hasError()'ized... And this would make code more consistent, since checking for PEAR_Errors from a class which never return any, will silently ignore all actual errors. See : class Foo { function Bar() {
      ...
      return false; // The usual 'false' error value
} } $test = Foo::Bar(); if (PEAR::isError($test)) <-- This won't detect anything With a hasError() inherited method, you'd get some "no such method" if the class is not compliant. Additionally what about this : if (!$bar = $foo->bar()) {
    echo $bar->popError();
} See ? You can use the convenient false value to indicate an error from the normal methods (not the constructor, of course...). If you receive false, then you retrieve the error informations with popError().
b) you are more likely to catch a error in a later method call, indicating that the object was not constructed properly..
Yes, but this forbids doing anything real in the constructor. It does not make any sense to write some Foo::init() (or whatever you call it) method, when initialization is precisely what a constructor is meant for.
try {
    $foo = new Foo($options);
} catch (InvalidOption $e) {
    ...
}
It's a very personal decision, but i really dont like the idea of assigments throwing errors too often, it makes the process of reading code, and guessing where you need to catch exceptions a little more complex: (eg. only method calls need to be try'd, or almost anything could throw an exception?)
I'm not talking about try'ing anything... It's just that exceptions look like a very smart way to trigger errors within a constructor. And anyway, The Zend engine helps you with the ones you forgot ;) Fatal error: Uncaught exception 'Exception' with message '...' -- og

« previous php.pear.dev (#32705) next »