tags:

views:

38

answers:

3

I'm reading some books on PHP (specifically "PHP and MySQL Web Development" by Welling and Thomson) and I'm also a fresh undergrad. I was a bit curious why the author decided to choose two different ways to terminate the execution of a function, e.g.

if (!$result) {
    throw new Exception('Password could not be changed.');
} else {
    return true;
}

For me, this seems a bit inconsistent and it would make more sense to return false and have the caller check the callee's return value and deal with it. Is it common for PHP code to be like this? Is this the type of style expected when using exceptions?

+1  A: 

Yes, I agree it doesn't make much sense. Either signal error conditions through the return value or with an exception. If the return value is always true (on error an exception is raised), you might as well not return anything (which in PHP is equivalent to returning NULL).

Artefacto
A: 

Most of the time when you see PHP code it will be all about the person who coded it and their particular style.

I don't see what is inconsistent about the code fragment. Exceptions are an appropriate way to deal with errors in most languages. He could omit the return statement but I know many people feel like a function should always return a value.

daedalus0x1a4
I feel that if this function were more consistent, then the return values should reflect that. The same way that strcmp() returns < 0, 0, or > 0, I feel like this would make more sense with consistent types for the return values. To be honest, we never learned much about exceptions and exception handling in college, so I'm not sure if this type of coding style is what I should expect in commercial code.
SHC
What we are looking at is just a code fragment. It is very hard to judge how to handle the flow of execution. Personally, I wouldn't throw an exception in an if else statement. I don't feel like wrapping the execution code in brackets is going to help it. In my opinion, as far as error handling, exceptions are the way to go because of try..catch blocks. It gives you an opportunity to correct or surpress error before halting execution.
daedalus0x1a4
A: 

It seems purely stylistic. I agree with you that returning true or false would be more consistent, and the calling code should throw an exception if false is unexpected or unacceptable.

I don't think the PHP community has fully worked out conventions for behavior such as this, so I wouldn't say it is either common or uncommon. There are a hundred different ways that systems like that are designed in PHP.

Alex JL