Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm developing a PHP login component which includes functions to manipulate the User object, such as $User->changePassword(string $old, string $new) What I need some advice with is how to return a status, as the function can either succeed (no further information needs to be given) or fail (and the calling code needs to know why, for example incorrect password, database problem etc.)

I've come up with the following ideas:

  • Unix-style: return 0 on success, another code on failure. This doesn't seem particularly common in PHP and the language's type-coercion messes with this (a function returning FALSE on success?) This seems to be the best I can think of.
  • Throw an exception on error. PHP's exception support is limited, and this will make life harder for anybody trying to use the functions.
  • Return an array, containing a boolean for "success" or not, and a string or an int for "failure status" if applicable.

None of these seem particularly appealing, does anyone have any advice or better ideas?

share|improve this question
What's wrong with PHP exceptions? Not knowing PHP they seem to be fairly Java-like to me. In Java the answer to me would be clearly to throw an exception and let the controller handle it. – sebastiangeiger Dec 14 '12 at 22:39
up vote 2 down vote accepted

I would lean toward using exceptions, because you are least likely to bypass or mishandle an error condition. If you have to define error codes or create custom structures, you have to account for those manually in the caller and callee.

If you forget that a critical error is (for example) the return integer 3, that won't necessarily prevent your code from entering an invalid state, or saving invalid data.

If you want to return multiple error reasons, you can always extend exceptions:

class MyException extends Exception
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";

    public function customFunction() {
        echo "A custom function for this type of exception\n";
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.