Re: Raising errors inside a constructor
| From: | Olivier Guilyardi | Date: | Tue, 17 Aug 2004 13:48:11 +0000 |
| Subject: | Re: Raising errors inside a constructor | ||
| References: | 1 2 3 4 5 6 7 8 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-32740@lists.php.net to get a copy of this message | ||
Greg Beaver wrote:
require_once 'PEAR/ErrorStack.php'; define('BERRY_ERROR_NOTMATURE', 1); define('BERRY_ERROR_NOTAFIELD', 2); define('BERRY_ERROR_TOOTINY', 1); class Berry {Thank you for helping me understand that :) I must say all of these static calls on the ErrorStack introduction page confused me. Now, ErrorStack seems indeed powerful. I guess it's not too hard to make a base class that uses ErrorStack. Then I'd subclass it to be able to do the much more clearer : if ($berry->hasError()) , instead of this PEAR_ErrorStack::staticHasErrors('berry') thing that will confuse 90% of the people who read my code. -- ogvar $field = null; function Berry($field) { if (!is_a($field, 'Field')) { PEAR_ErrorStack::staticPush('berry', BERRY_ERROR_NOTAFIELD, 'error', array('field' => $field), 'parameter is not a field!'); return; } // add a hypothetical if ($field->size() < 25) { PEAR_ErrorStack::staticPush('berry', BERRY_ERROR_TOOTINY, 'warning', array('size' => $field->size), 'Field size "%size%" is too tiny to support lindenberries'); } if (!$field->isMature()) { PEAR_ErrorStack::staticPush('berry', BERRY_ERROR_NOTMATURE, 'error', array(), 'Sorry, this field\'s berries are too young'); return; } }echo "Berry counter v0.45.12\n"; $berry = new Berry($field); if (PEAR_ErrorStack::staticHasErrors('berry')) {$e = PEAR_ErrorStack::staticGetErrors(); foreach ($e['berry'] as $error) { echo $e['message'] . "\n"; } exit;} if (($c = $berry->count()) !== false) {echo "There's $c berries. It's time to go and pick them !\n";} else {$e = PEAR_ErrorStack::staticGetErrors(); foreach ($e['berry'] as $error) { echo $e['message'] . "\n"; } exit;} As you can see, it's the same number of lines of code, and would actually be slightly faster than the code you've written, with the added flexibility that you can raise multiple errors in the constructor (as in my example) and also have support for warnings and so on.