9.10 Returning an Error Object on Failure


You want to return a valid object from your class on success, and an error object on failure.

Technique

Create an is_error method in your class, which will find out whether you are returning an error object:

 <?php class SomeClass {     var $somevar;     function some_method ($var) {         $this->somevar = $var;         if ($this->somevar != $var) {             $errobj = new SomeClassError;             $errobj->_code = -2;             $errobj->_message = 'Couldn't assign $var to $somevar';             return($errobj);         } else {             return(1);         }     }     function is_error ($val) {         return is_object($val) &&               (get_class($val) == "SomeClassError"                 is_subclass_of($val, "SomeClassError");     } } class SomeClassError {     var $_code;     var $_message;     function getCode() {         return($this->_code);     }     function getMessage() {         return($this->_message);     } } $obj = &new SomeClass; $ret = $obj->some_method("Aqualung"); if (SomeClass::is_error($ret)) {     die(sprintf('Error [%d]: %s', $ret->getCode(), $ret->getMessage()); } // .. Manipulate the SomeClass object here ?> 

Comments

Returning an error object from a class enables you to return a more specific message to the programmer using your class than just a simple error code or a message. In turn , that enables the programmer to print out a more useful message to the end user .



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net