Re: Raising errors inside a constructor
| From: | Olivier Guilyardi | Date: | Mon, 16 Aug 2004 18:29:13 +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-32708@lists.php.net to get a copy of this message | ||
Hi Hans,
Hans L wrote:
As I stated in my last reply to Alan, I would use the same style of error handling for both methods and the constructor. Additionally, this would make it nicer for methods, using the usual false return value (as in 99% of the php api functions) : if (!$bar = $foo->bar()) {$foo = new Foo($options); if ($foo->hasError()) { ... }What you are describing seems to be PEAR_ErrorStack-style error handling. While there's nothing wrong with this, I think it's good to recognize that if you introduce that for your constructor only (and use return-based error handling elsewhere) then you have created a class that uses different styles of error handling. That could be confusing.
echo $bar->popError();}
If you plan to use stack based error handling everywhere then you aren't really proposing anything new or different ;) -- i.e. AFAIK this is the officla way to implement PEAR_ErrorStack error handling. You could create a baseclass if you wanted; ideally (PHP5) this would be an interface (MyClass implements IStacksErrors). Of course in PHP5 it's a moot point, since there are exceptions.Forget the stack, I used 'pop' just to mean that it could be stack based, but it's not my point. Yeah, creating a baseclass, that's it. My actual classes would all be children of this baseclass, and, as such, would inherit its error handling capabilities, including the hasError() and popError() methods.
More generally, I'd suggest that perhaps you're trying to do too much in your constructor if you need this feature. With PHP5 it's not a big deal, but in PHP4 it obviously gets ugly. Introducing a mixed-mode error handling just to handle this special case seems like a bad idea (IMHO, of course).No mixed-mode error-handling, read above. It's not a matter of doing too much in the constructor, it is a matter of using the constructor to initialize the object. Isn't it what constructors are all about ? Take, for example, XML_Serializer, its constructor accepts an $options argument. This is good, it's not asking too much to a constructor. But it does not check if these options are valid (for example: what if I forget a 't' in "scalarAsAttributes" ?). Actually, it can't. -- og